17

Django: Putting Form Values in the URL Query String

 3 years ago
source link: https://snakeycode.wordpress.com/2019/05/03/django-putting-form-values-in-the-url-query-string/
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: 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK