Reputation: 1742
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
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
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