Which is the best way to validate errors in Django?
Question:
I found that there is a lot of ways to validate errors in Django, I’m just wondering which one is preferable and why?
e.g.
-
using clean in form, like:
deadline = self.cleaned_data.get('deadline')
if datetime.strptime(str(deadline)[:19], '%Y-%m-%d %H:%M:%S') < datetime.today():
raise forms.ValidationError(_('Deadline cannot be in past!'))
return deadline
-
before saving we can validate if there is any error and sending the instance if everything right, like:
def save(self, force_insert=False, force_update=False, *args, **kwargs):
if datetime.strptime(str(deadline)[:19], '%Y-%m-%d %H:%M:%S') < datetime.today():
raise forms.ValidationError(_('Deadline cannot be in past!'))
else:
super(MODEL, self).save(force_insert, force_update, *args, **kwargs)
-
and not forgetting the validators in the model where I can use one in the filed it self like:
deadline = models.DateTimeField(
verbose_name=_('deadline'),
validators=[MaxValueValidator(datetime.datetime.today())],
help_text=_('Note that the end time will be at the midnight of the day you picked.'),
)
Also, we can do that in the forms in the class form we can check before saving if everything is right.
I want to know which is the best as a programmer and write a professional code.
Answers:
the best way to validate model is using
clean_fields the reason is when an error occurs in the clean_fields it shows only for that particular field and this error is for validation one field
class ContactForm(forms.Form):
message = forms.CharField(widget=forms.Textarea)
def clean_message(self):
message = self.cleaned_data['message']
message = message.replace('a', '') # remove all "a"s from message
if len(message) >= 5:
raise ValidationError('Too many characters ...')
return message
In MVC, anything that touches the database should be in the model layer. You could have a method like ‘is_valid_email(…)’ on the User model and call that from your Form.
Note that the Model layer doesn’t mean that you have to have a Class per table in your database VS creating new classes.
The Form is the Controller in DRF, I would go with option 1.
I found that there is a lot of ways to validate errors in Django, I’m just wondering which one is preferable and why?
e.g.
-
using clean in form, like:
deadline = self.cleaned_data.get('deadline') if datetime.strptime(str(deadline)[:19], '%Y-%m-%d %H:%M:%S') < datetime.today(): raise forms.ValidationError(_('Deadline cannot be in past!')) return deadline
-
before saving we can validate if there is any error and sending the instance if everything right, like:
def save(self, force_insert=False, force_update=False, *args, **kwargs): if datetime.strptime(str(deadline)[:19], '%Y-%m-%d %H:%M:%S') < datetime.today(): raise forms.ValidationError(_('Deadline cannot be in past!')) else: super(MODEL, self).save(force_insert, force_update, *args, **kwargs)
-
and not forgetting the validators in the model where I can use one in the filed it self like:
deadline = models.DateTimeField( verbose_name=_('deadline'), validators=[MaxValueValidator(datetime.datetime.today())], help_text=_('Note that the end time will be at the midnight of the day you picked.'), )
Also, we can do that in the forms in the class form we can check before saving if everything is right.
I want to know which is the best as a programmer and write a professional code.
the best way to validate model is using
clean_fields the reason is when an error occurs in the clean_fields it shows only for that particular field and this error is for validation one field
class ContactForm(forms.Form):
message = forms.CharField(widget=forms.Textarea)
def clean_message(self):
message = self.cleaned_data['message']
message = message.replace('a', '') # remove all "a"s from message
if len(message) >= 5:
raise ValidationError('Too many characters ...')
return message
In MVC, anything that touches the database should be in the model layer. You could have a method like ‘is_valid_email(…)’ on the User model and call that from your Form.
Note that the Model layer doesn’t mean that you have to have a Class per table in your database VS creating new classes.
The Form is the Controller in DRF, I would go with option 1.