4👍
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 ModelForm
s 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 Form
s and ModelForm
s.
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....