Django form field different clean logic based on UpdateView or CreateView

Viewed 221

I have a form in Django that is used in both a CreateView and an UpdateView. One of the field is hours_allocated which cannot be < 0. In my model, I have declared it as:

hours_allocated= models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(Decimal('0.0')), MaxValueValidator(Decimal('24.00'))])

When the record is updated (UpdateView) this is fine. However, in the CreateView, I would like to ensure that the value is > 0 (not = 0.0 as allowed in UpdateView). If I add a clean_hours_allocated() method to check if the value is > 0, it applies to both the CreateView and UpdateView.

Is there a way to have different validation at the form level based on whether the form is used in an UpdateView or CreateView? Or, is there a way to properly handle validation in the view itself?

2 Answers

I'm not an expert on Django. However, I think you could do something like this in forms.py.

def clean_hours_allocated(self):
    if not self.instance.pk: # Update instances have a pk and wouldn't go in this.
        ## Logic to validate Create Instances

    return hours_allocated

I don't think this is the perfect solution, but I believe this should fulfill your task.

I believe one approach would be adding a hidden field to your form called something like mode which must be one of {'create', 'update'}. Then you set the value of this field appropriately based on the view which instantiates the form.

Once this is in place, you could check cleaned_data['mode'] in your desired validation method (see Django's docs for a detailed explanation of the options). Depending on its value, an if-else branch would allow you to apply validation logic differently

Related