EralpB
EralpB

Reputation: 1742

Django form save error after is_valid return true

What is the best practice to handle the errors on form.save()? For example email unique check will be done in save on database level, not on is_valid().

def user_registration(request):
    from accounts.forms import UserRegistrationForm
    form = UserRegistrationForm(request.POST)
    if not form.is_valid():
        return {
            'errors': form.errors.as_json(escape_html=False)
        }
    ### This can still return error, how to handle it? try catch?
    user = form.save()
    return {
        'user': user.id,
    }

Upvotes: 0

Views: 591

Answers (2)

Mohit Solanki
Mohit Solanki

Reputation: 2130

Ideally, there should be clean_email method on the form class that checks if the email already exists. save method should be called after all the validation is done.

Upvotes: 1

Lemayzeur
Lemayzeur

Reputation: 8525

Catch the email before reaching the form validation. You can do something like

if request.method == 'POST':
     email = request.POST.get("email")
     if User.objects.filter(email__iexact=email).exists():
         form.add_error("email","Email exists")

     if not form.is_valid():
         return {
             'errors': form.errors.as_json(escape_html=False)
         }
     user = form.save()

Upvotes: 0

Related Questions