Django: Passing Form Values in URL

 4个月前 阅读数 3
以下为 快照 页面,建议前往来源网站查看,会有更好的阅读体验。
原文链接: https://snakeycode.wordpress.com/2020/05/05/django-passing-form-values-in-url/


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.