Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing POST data in Django form

Tags:

python

django

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]?

like image 474
murgatroid99 Avatar asked Jun 29 '11 15:06

murgatroid99


People also ask

How can I get form data in POST request?

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.

What is post method in Django?

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.

What are request get and request post objects?

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.


1 Answers

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']
like image 57
Yuji 'Tomita' Tomita Avatar answered Sep 24 '22 00:09

Yuji 'Tomita' Tomita