Django Field errors not displaying
Here is my forms.py code:
from .models import User
class userRegistrationForm(forms.ModelForm):
password = forms.CharField(widget = forms.PasswordInput())
confirm_password = forms.CharField(widget = forms.PasswordInput())
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email','password'] ```
Here is my views.py code:
```
def registerUser(request):
if request.method == 'POST':
print(request.POST) #request.POST, WE ARE GETTING THE DATA HERE.
form = userRegistrationForm(request.POST)
if form.is_valid():
# CREATE THE USER, USING THE FORM
# password = form.cleaned_data['password']
# user = form.save(commit=False) #FORM IS READY TO BE SAVED, BUT NOT YET SAVED. BCZ OF COMMIT
# user.role = User.CUSTOMER
# user.set_password(password)
# user.save()
# CREATE THE USER, USING create_user METHOD.
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(first_name=first_name, last_name=last_name, username=username, email=email, password=password)
user.role = User.CUSTOMER
user.save()
#print("User is created")
return redirect('registerUser')
else:
print("Invalid form")
print(form.errors)
else:
form = userRegistrationForm()
form = userRegistrationForm()
context = {
'form':form
}
return render(request, 'accounts/registerUser.html', context)
Here is my registerUser.html code:
<ul class="errorlist">
{% for field in form %}
{% if field.errors %}
{% for error in field.errors %}
<li style="color: red;">{{error}}</li>
{% endfor %}
{% endif %}
{% endfor %}
</ul>
Technically my error should be shown here in red color:
[enter image description here][1]
[1]: https://i.sstatic.net/2fVh2q4M.png
But it is not showing, The errors are showing in my terminal, but not on the html page. I am struggling to understand the error. Can anyone help me fix this issue? The tutorial I am following, he do the same thing as I did, but his errors are showing.
You create a new form when the form validation failed, so there are no errors anymore:
def registerUser(request):
if request.method == 'POST':
form = userRegistrationForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(
first_name=first_name,
last_name=last_name,
username=username,
email=email,
password=password,
)
user.role = User.CUSTOMER
user.save()
return redirect('registerUser')
else:
print('Invalid form')
print(form.errors)
else:
form = userRegistrationForm()
# no form = userRegistrationForm()
context = {'form': form}
return render(request, 'accounts/registerUser.html', context)