I have been using this site as an example of how to make a dynamic form in Django. In his view he uses
if request.method == 'POST':
form = UserCreationForm(request.POST)
to pass the data into the form and in the form constructor he uses
extra = kwargs.pop('extra')
to access the POST data. I tried to do something similar with my view:
def custom_report(request):
if request.method=='POST':
form=CustomQueryConstraintForm(request.POST)
else:
form=CustomQueryConstraintForm()
return render(request, 'frontend/custom_report.html', {'form':form})
In my form constructor I printed args
and kwargs
and found that kwargs
is empty and args
is a tuple containing the QueryDict
that in turn contains the POST data. If I try instead to use form=CustomQueryConstraintForm(**request.POST)
, each element in kwargs
is a list containing the value of the field as its only element. Am I doing something wrong here? If not, is there a more elegant way of accessing the data than args[0][element_name][0]
?
To post HTML form data to the server in URL-encoded format, you need to make an HTTP POST request to the server and provide the HTML form data in the body of the POST message. You also need to specify the data type using the Content-Type: application/x-www-form-urlencoded request header.
Django's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.
So, to request a response from the server, there are mainly two methods: GET : to request data from the server. POST : to submit data to be processed to the server.
That is expected behavior for forms: the POST data you pass into the form is the first argument, args[0] and not a keyword argument. What are you looking for?
data = args[0]
print data['my_field']
and in the form constructor he uses extra = kwargs.pop('extra') to access the POST data.
kwargs.pop('extra')
is not getting POST data. It is a list of questions associated with that given user -- some scenario given by the author that the "marketing department" handed you.
In any case, if you need to access the post data at any point in a form, I find self.data
the cleanest which is set in forms.__init__
.
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.data['my_field']
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