5

Django: Putting Form Values in the URL Query String

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

Standard

Django: Putting Form Values in the URL Query String

I used to avoid using URLs with long query strings. This was partially due to an essay I read by a Big Shot about how URLs should be beautiful. Not sure I agree any more.

My use case is the user enters some filter parameters, a database query is run and a report is generated. Putting the filter parameters in the query string allows users to return to the page at another time or to share the link.

Here is the code:

from django.views.generic.edit import FormView
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils.http import urlencode
class MyFormView(FormView):
def form_valid(self, form):
base_url = reverse('filter_tickets_result')
# Post process some fields
if form.cleaned_data['job']:
form.cleaned_data['job'] = form.cleaned_data['job'].id
qs = urlencode(form.cleaned_data)
return HttpResponseRedirect(base_url + '?' + qs)

Note, I am using the Django version of urlencode. This avoids issues with Python 2.X and 3.X.


猜你喜欢

关于极客头条


聚合每日国内外有价值,有趣的链接。