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.
-
[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. -
[views.py: get_initial] We can access the variable we want with
self.kwargs['iid']
and use it to set the initial value of theident
fields which links back to the Banker object -
[views.py: get_success_url] In the same way we can pass the value into the form's success_url to point at URL2
-
[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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.