Django: Passing Form Values in URL
source link: https://snakeycode.wordpress.com/2020/05/05/django-passing-form-values-in-url/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Standard
Django: Passing Form Values in URL
Lets say you have a form that is used to drive the next page. For example, it might contain parameters for running a report. One way to handle this is to pass the parameters to the report view and run the report in the get_context section of that view.
If you only have a few simple parameters, you could put them as part of the URL. In the past, I would put them in the session and pull them from the session for the report view. This turned out to be a bad choice because users would save the report URL and return to it later; maybe the next week. By that time the session data would no longer be available.
An approach that avoids this problem is to put the form data into the query string of the url. Here is how to do that:
from
django.utils.http
import
urlencode
from
django.core.urlresolvers
import
reverse
def
form_valid(
self
, form):
qs
=
urlencode(form.cleaned_data)
url
=
'?'
.join([reverse(
'my_report'
), qs])
return
HttpResponseRedirect(url)
You may want to alter some of the form.cleaned data to make it easier to use in the report view. For example, if one of the form fields returns an instance, replace the instance with the instance ID.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK