Login

Snippets by blacktav

Snippet List

Accessing URL variable from within a Form

**Use case:** 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. ** How To:** 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. 1. [urls.py] Models *Banker* and *Iaccount* are related as One-to-Many so if we are creating an *Iaccount* we cannot usually determine the *Banker* 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. 2. [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 *Banker* object 3. [views.py: get_success_url] In the same way we can pass the value into the form's *success_url* to point at URL2 4. [template] In the template, we can also access the variable now as `form.ident.value` so we can construct a *Go Back* link to URL2 Thanks to Thomas Orozco for leading the way.

  • url
  • form
  • cbv
Read More

blacktav has posted 1 snippet.