[Django]-Django form field different clean logic based on UpdateView or CreateView

2👍

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.

👤dab92

0👍

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

Leave a comment