Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple values be used in django a model validator?

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])
like image 976
markwalker_ Avatar asked Sep 28 '12 11:09

markwalker_


People also ask

How does validation work in Django?

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.

How do I increase validation error in Django?

To create such an error, you can raise a ValidationError from the clean() method. For example: from django import forms from django. core.

What does validators do in the code field validators?

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.


1 Answers

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)
like image 161
schacki Avatar answered Sep 20 '22 15:09

schacki