[Fixed]-Django get_or_create only if form constraints are met

1👍

✅

How about changing your comparison, by first checking if your form is valid in clean()?

def clean(self):
    ...
    if not artist:
        raise ValidationError("artist is a required field")
    if not title:
        raise ValidationError("title is a required field")
    ...

The above makes it a two-step process for the user, since if a user leaves both artist and title blank, they ony get the artist notice.
You could make a better (sub) if statement and a combined ValidationError, or solve that by using clean_artist and clean_title, just for raising the ValidationError (not using get_or_create in the field clean methods):

def clean_artist(self):
    # no get_or_create here
    ...
    if not artist:
        raise ValidationError("artist is a required field")

def clean_title(self):
    # no get_or_create here
    ...  
    if not title:
        raise ValidationError("title is a required field")

def clean(self):
    ...
    if title and artist:
        # get_or_create stuff here
    ...

This way, you should get both errors independently, but the get_or_create is still done in the main clean, only if title and artist are valid.

Leave a comment