Login

Accessing URL variable from within a Form

Author:
blacktav
Posted:
September 1, 2013
Language:
Python
Version:
1.5
Tags:
url form cbv
Score:
0 (after 0 ratings)

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# urls.py
# URL1
url(r'^banker/(?P<iid>\d+)/iac$', 
    view = IacCreateView.as_view()),
# URL2
url(r'^banker/(?P<pk>\d+)/$', 
    view = BankerDetailView.as_view(),
    name='banker'),

# forms.py
class IaccountForm(forms.ModelForm):
    class Meta(object):
        model = Iaccount

# views.py
class IacCreateView(LoginRequiredMixin, CreateView):
    template_name = 'iaccount_form.html'
    model = Iaccount
    form_class = IaccountForm

    def get_initial(self):
        initials = super(IaccountCreateView, self).get_initial()
        initials['ident'] = self.kwargs['iid']
        return initials

    def get_success_url(self):
        pk = self.kwargs['iid']
        return reverse('banker', kwargs={'pk': pk})

# template iaccount_form.html
...
<a href="{% url 'banker' form.ident.value %}">go back</a>
...

More like this

  1. Complex Form Preview by smagala 6 years, 3 months ago
  2. Complex Formsets, Redux by smagala 5 years, 3 months ago
  3. Improved Pickled Object Field by taavi223 5 years, 10 months ago
  4. @url decorator improvements by davepeck 5 years, 11 months ago
  5. Simple Plone Migration by msm-art 7 years, 5 months ago

Comments

Please login first before commenting.