I've got a model using a validation class called CompareDates
for my model validators and I want to pass the validator two field values. However I'm unsure of how to use multiple field values in a validator.
I want to be able to make comparisons between the dates in order to validate the model as a whole but it doesn't seem like you can keyword the values passed to the validators, or am I missing something?
from django.db import models
from myapp.models.validators.validatedates import CompareDates
class GetDates(models.Model):
"""
Model stores two dates
"""
date1 = models.DateField(
validators = [CompareDates().validate])
date2 = models.DateField(
validators = [CompareDates().validate])
Django provides built-in methods to validate form data automatically. Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data. The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class.
To create such an error, you can raise a ValidationError from the clean() method. For example: from django import forms from django. core.
A validator is a function that takes in the fields new value, and then acts on it. They are a simple way to customize a field. They allow you to trigger functionality when a field's value changes, modify input, or limit which values are acceptable.
The "normal" validators will only get the current fields value. So it will not do what you are trying to do. However, you can add a clean method, and - if need should be - overwrite your save method like that:
class GetDates(models.Model):
date1 = models.DateField(validators = [CompareDates().validate])
date2 = models.DateField(validators = [CompareDates().validate])
def clean(self,*args,**kwargs):
CompareDates().validate(self.date1,self.date2)
def save(self,*args,**kwargs):
# If you are working with modelforms, full_clean (and from there clean) will be called automatically. If you are not doing so and want to ensure validation before saving, uncomment the next line.
#self.full_clean()
super(GetDates,self).save(*args,**kwargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With