Задать вопрос

Тел: +7 965 3737 888





Accessing URL variable from within a Form

<p><strong>Use case:</strong></p>
<p>Suppose you are working on maintenance screens on some data objects. On one particular page (a form) you want to have exits directly back to a calling page (as a cancel operation) or indirectly back to the calling page (after an data update operation). However, the form and its object are not directly related to the target page (perhaps a one-to-many relationship) so you cannot figure the calling page from object data - but the target object IS referenced in the url.</p>
<p><strong> How To:</strong></p>
<p>To make this work, we need to pick out a variable from the URL of the current page and use it to generate the URL of the target page.</p>
<p>[urls.py] Models <em>Banker</em> and <em>Iaccount</em> are related as One-to-Many so if we are creating an <em>Iaccount</em> we cannot usually determine the <em>Banker</em> object to return to. In this example, URL1 contains the variable iid - the primary key to the Banker object; this will render a create form. We want to be able to reference URL2 from this form.</p>
<p>[views.py: get_initial] We can access the variable we want with self.kwargs['iid'] and use it to set the initial value of the ident fields which links back to the <em>Banker</em> object</p>
<p>[views.py: get_success_url] In the same way we can pass the value into the form's <em>success_url</em> to point at URL2</p>
<p>[template] In the template, we can also access the variable now as form.ident.value so we can construct a <em>Go Back</em> link to URL2</p>
</ol><p>Thanks to Thomas Orozco for leading the way.</p>

Вопрос полезен? Да0/Нет0