开发者

Accessing POST data in Django form

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 = UserCreat开发者_StackOverflow中文版ionForm(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]?


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 I understand correctltly, after a POST request you are trying to redisplay the same form page in which the form fields are filled, right? If yes, this is what you need:

form = CustomQueryConstraintForm(initial=request.POST)


You can also access the form data through the cleaned_data dictionary after using the is_valid() method. Like this:

jobForm = JobForm(request.POST)
jobForm.is_valid()
jobForm.cleaned_data

it's a dictionary of the values that have been entered into the form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜