skip to Main Content

I have a Django models with a DurationField. I would like that the users cannot put a value over 00:09:59. Unfortunately I could not find any information to do this in the doc : https://docs.djangoproject.com/en/4.1/ref/models/fields/#durationfield

2

Answers


  1. You can add validators for that.

    It will look something like:

    DurationField(
        validators=[MaxValueValidator(datetime.timedelta(minutes=10)]
        )
    
    Login or Signup to reply.
  2. It is not possible with default DurationField.

    You can override the clean_%s method in the form:

    from django import forms
    
    
    class YourForm(forms.Form):
        duration_field = forms.DurationField()
    
        def clean_duration_field(self):
            data = self.cleaned_data['duration_field']
            if value > timedelta(minutes=9, seconds=59):
                raise forms.ValidationError("....", code="invalid")
            
            return data
    
    

    If you need to do this validation in many places, you can create a custom Field for overriding the validating method of field:

    from django import forms
    from django.core.validators import validate_email
    
    class RestrictedDurationField(forms.DurationField):
    
        def __init__(self, limit: timdelta, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.limit = limit
    
        def validate(self, value):
            super().validate(value)
            if value > self.limit:
                raise forms.ValidationError("....", code="invalid")
    
    
    # and usage
    class form(Form):
        duration_field = RestrictedDurationField(limit=timedelta(minutes=9, seconds=59), ...)
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search