I want to take a ready-made form (i.e an object of a class derived from django.Forms.form with validated bound data) and urlencode it as though it were submitted with GET. Is there a built-in way?
To show why I'm asking this questino, and why I can't just call urlencode, the output from this should be "box=on".
from django import forms
from urllib import urlencode
class DemoForm(forms.Form):
box = forms.BooleanField(required=False)
instance = DemoForm({"box": True}) # it's irrelevant how this data is supplied
instance.is_valid()
print "encoded:", urlencode(instance.cleaned_data)
In fact it's "box=True", because urlencode isn't encoding the form it's encoding the cleaned values (and believe me, BooleanField is the simplest case).
So I'm asking for a way to encode the form as though it were a GET string. A correct GET string.
Calling urllib's urlencode on the form's cleaned_data won't work well in two cases:
To deal with both of these problems, use the form's built-in urlencode function:
form = MyForm(request.POST) #or a dict or whatever
form.is_valid()
querystring = form.data.urlencode()
Note that this is called on data, not cleaned_data. If your form changes values as part of validation, those changes won't be reflected here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With