I am creating a registration form using the Django framework and I want to display some error messages to the user if they enter the wrong confirm password, or an email already taken etc. I have written the code and it seems to be working, but I can't seem to get the messages to show on screen upon redirecting to back to registration page if there is an error in the form. I have imported messages on the views.py page (from django.contrib import messages) and I think my setting.py is all configured correct:
https://i.stack.imgur.com/oqvJN.png[
^]
Here is my code for views.py:
def register(request):
if request.method == "GET":
register_form = RegisterForm()
return render(request, "main/register.html", {
'form': register_form
})
else:
register_form = RegisterForm(request.POST)
if register_form.is_valid():
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
confirm_password = request.POST['confirm_password']
if password == confirm_password:
if User.objects.filter(email=email).exists():
messages.info(request, 'Email or user name Already taking')
return redirect('register')
elif User.objects.filter(username=username).exists():
messages.info(request, 'username is taken')
return redirect('register')
else:
User.objects.get_or_create(username=username,
first_name=first_name, last_name=last_name, email=email,
password=password)
return redirect('main/login.html')
else:
messages.error(request, 'Password Not Match')
return redirect('register')
#return redirect ('/')
else:
return render(request, 'main/login.html')
and my code for the register form:
<form action="{% url 'register' %}" method="POST">
{% csrf_token %}
<fieldset>
<legend>Enter details</legend>
<ul>
{{ form.as_table }}
<button type="submit" class="mybutton _f-purple" value="submit">Register</button>
</ul>
</fieldset>
</form>
Thanks in advance to anyone that can help :)
What I have tried:
I have checked all settings are correct and have tried my webpage to view it's behaviour when form information is invalid