How to access data when form.is_valid () is false

When I have a valid Django form, I can access the data using form.cleaned_data. But how can I get the data entered by the user when the form is invalid, i.e. Form.is_valid is false.

I am trying to access forms in a form set, so form.data seems to just confuse me.

+42
python django forms formset
Apr 09 '09 at 19:16
source share
7 answers

you can use

form.data['field_name'] 

This way you get the original value assigned to the field.

+38
Sep 17 '09 at 18:36
source share
β€” -

See http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation

Secondly, as soon as we decide that the combined data in two fields is considered invalid, we must remember to remove them from cleaned_data.

In fact, Django is now completely destroying cleared_data if there are any errors in the form. However, this behavior may change in the future, so it is not a bad idea to clean up after yourself in the first place.

Raw data is always available in request.POST .




The comment says the point is to do something like a more complex field level check.

Unapproved data is assigned to each field and either returns valid data or throws an exception.

In each field, any check for the original content can be done.

+17
Apr 09 '09 at 19:27
source share

I struggled with a similar issue and came across a great discussion here: https://code.djangoproject.com/ticket/10427

This is not well documented, but for a live form, you can view the value of a field - as seen from widgets / users - with the following:

 form_name['field_name'].value() 
+12
Jun 12 2018-12-12T00:
source share

You can use this template:

 class MyForm(forms.Form): ... def clean(self): self.saved_data=self.cleaned_data return self.cleaned_data 

In your code:

 if form.is_valid(): form.save() return django.http.HttpResponseRedirect(...) if form.is_bound: form.saved_data['....'] # cleaned_data does not exist any more, but saved_data does. 

Using form.data is not a good solution. Causes:

  • If the form has a prefix, the dictionary keys will have a prefix with this prefix.
  • Data in form.data is not cleared: only string values ​​exist.
+5
May 27 '11 at 12:17
source share

I have many methods. All that you can choose.

I assume the form is as follows:

 class SignupForm(forms.Form): email = forms.CharField(label='email') password = forms.CharField(label='password', widget=forms.PasswordInput) 

1-1. Receive from request

 def signup(req): if req.method == 'POST': email = req.POST.get('email', '') password = req.POST.get('password', '') 

2-1. Get the raw value assigned to this field and return the value of the data attribute of the field

 def signup(req): if req.method == 'POST': ... sf = SignupForm(req.POST) email = sf["email"].data password = sf["password"].data ... 

2-2. Get the original value assigned to the field and return the value of the value attribute of the field

 def signup(req): if req.method == 'POST': ... sf = SignupForm(req.POST) email = sf["email"].value() password = sf["password"].value() ... 

2-3. Get dictionary assigned to fields

 def signup(req): if req.method == 'POST': ... sf = SignupForm(req.POST) # print sf.data # <QueryDict: {u'csrfmiddlewaretoken': [u'U0M9skekfcZiyk0DhlLVV1HssoLD6SGv'], u'password': [u''], u'email': [u'hello']}> email = sf.data.get("email", '') password = sf.data.get("password", '') ... 
+5
Jul 07 '15 at 7:50
source share

I had a similar problem using a set of forms. In my example, I wanted the user to select the first option before the second choice, but if the first choice hit another error, the error "select the first choice to the second" was also displayed.

To capture the 1st unclean field data, I used this in a clean form field method:

 dirty_rc1 = self.data[self.prefix + '-reg_choice_1'] 

Then I could check for data in this field:

 if not dirty_rc1: raise ValidationError('Make a first choice before second') 

Hope this helps!

+3
Mar 21 2018-12-12T00:
source share

You access the data either from the clean () method of the field, or from the clean () method of the form. clean () is a function that determines if a form is valid or not. It is called when is_valid () is called. In the clean () form, you have a cleaned_data list when you can run your own code to make sure everyone checks it. You also have clean () in the widget, but it uses one passed variable. To access the field clean () method, you will have to subclass it. eg:.

 class BlankIntField(forms.IntegerField): def clean(self, value): if not value: value = 0 return int(value) 

If you want an IntField that does not choke on an empty value, for example, you should use the above.

clean () as a kind of similar work:

 def clean(self): if self.cleaned_data.get('total',-1) <= 0.0: raise forms.ValidationError("'Total must be positive") return self.cleaned_data 

You can also have a clean_FIELD () function for each field so that you can check each field separately (after calling the clean () field)

+1
Aug 16 '09 at 22:54
source share



All Articles