Django test no field validation errors

What is the django way to check for non-field validation errors?

For example, an email field will verify that the entered text is a valid email address, but not a field error will be displayed above the form, without regard to any field. For example, he would say that this email address is already registered.

When testing applications, how do you test these off-field validation errors?

Edit: To make the question more clear. I have a custom validation function, but I would like to verify that it throws errors that it should use using the unittest frame provided by Django.

I could call the function directly and test it this way, but this does not guarantee that it is used correctly in the view (i.e. I want to do an integration test).

Thanks.

Edit: I found a solution on how to check , not check a field error.

Running with assertFormError. Change the field name to None and change the error line to a list of error lines.

self.assertFormError(response, 'form', 'field name', 'error') # Test single field error self.assertFormError(response, 'form', None, ['Error #1.', 'Error #2']) # Test general form errors 
+4
source share
2 answers

Just for the correct answer, even if it is already in the question itself, I will send the answer.

You can check the error form using assertFormError() .

It is claimed that the form field returns a list of errors when rendering on the form.

Note that the form name must be the name of the form in context not the actual form that you use for validation.

You can use it for non_field_errors (common errors not related to any field):

 self.assertFormError(response, 'form', None, 'Some error') 

You can test a specific field error as follows:

 self.assertFormError(response, 'form', 'field_name', 'Some error') 

You can also pass a tuple of errors for testing.

 errors = ['some error 1', 'some error 2'] self.assertFormError(response, 'form', 'field_name', errors) 
+2
source

write a custom function that checks the fields and is called instead of form.is_valid ().

Django docs provides a detailed description of this. check out the link below.

https://docs.djangoproject.com/en/dev/ref/forms/validation/#form-field-default-cleaning

For example: from django import forms

 class ContactForm(forms.Form): subject = forms.CharField(max_length=100) email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea) def clean_message(self): message = self.cleaned_data['message'] num_words = len(message.split()) if num_words < 4: raise forms.ValidationError("Not enough words!") return message 

Herr clean_message will be my special check method

0
source

All Articles