سؤال

I don't understand this behaviour. Let's say I open a Django shell and type:

from django.contrib.auth.models import User
user = User.objects.create(username="toto", email="titi")

Why does Django let me create this user (with an invalid email) without raising an error?

I have the same "no verification behaviour" creating a user in a POST in my API created with tastypie.

The question is:

As Django does not seem to check this by itself, where am I supposed to perform this kind of verifications sothat I don't have to write them several times (since a user can be created in several ways like website, API, etc.)?

Thanks.

هل كانت مفيدة؟

المحلول

Django doesn't implicitly do any validation if you just call .create() or .save() - you need to explicitly use model validation, or save the object via a ModelForm. Your example with model validation would look like this:

user = User(username="toto", email="titi")
try:
    user.full_clean()
except ValidationError as e:
    # handle the error...
    pass
user.save()

Or using a ModelForm:

class UserForm(forms.ModelForm):
    class Meta:
        model = User

f = UserForm(dict(username="toto", email="titi"))
if f.is_valid():
    user = f.save()
else:
    # handle error, ...
    pass

Both model validation and ModelForms invoke the model field's validators, so in the case of the User's email, no additional work is needed for validation. If you need to do custom validation, you can do this in the ModelForm class - it is common to have a forms.py file in the app as a central place for Forms and ModelForms.

The same goes for Tastypie - the default configuration assumes the data submitted is valid. You can override this with the FormValidation class, which uses a Django Form or ModelForm for its validation. A full example would look something like this:

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        validation = FormValidation(form_class=UserForm)  # UserForm from above
        # more options here....
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top