Django form field different clean logic based on UpdateView or CreateView

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?


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.