I want to register users.
So I made a:
class RegisterForm(ModelForm):
class Meta:
model=User #(from django.auth.contrib.User)
now i display that form in a template for the users to fill it and to submit it.
When i do form.is_valid(), i get this validation error: Your username and password didn't match. Please try again.
Does anyone know what can cause this?
i’ve included the ModelForm, the view that processes the registration form and the template that displays the registration form.
Thank you for your time and kind concern.
MY MODEL FORM
class RegisterForm(ModelForm):
class Meta:
model=User
THE VIEW THAT HANDLES THE REGISTRATION
def register(request):
if request.method=='POST':
form=RegisterForm(request.POST)
if form.is_valid(): # HERE I GET A VALIDATION ERROR
new_user=User.objects.create_user(username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
email=form.cleaned_data['email'],
)
new_user.is_active=True
new_user.first_name=form.cleaned_data['first_name']
new_user.last_name=form.cleaned_data['lastname']
return HttpResponseRedirect(reverse('confirm_registered'),args=[form.cleaned_data['username']])
else:
return render(request,'login/register.html',{'form':form})
else:
raise ValueError()
THE REGISTRATION TEMPLATE
{% extends "store/index2.html" %}
{% block canvas %}
<h3>Registration</h3>
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="/retailstore/login/register.html">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
<tr>
<td>{{ form.first_name.label_tag }}</td>
<td>{{ form.first_name }}</td>
</tr>
<tr>
<td>{{ form.last_name.label_tag }}</td>
<td>{{ form.last_name }}</td>
</tr>
<tr>
<td>{{ form.email.label_tag }}</td>
<td>{{ form.email }}</td>
</tr>
</table>
<input type="submit" value="register" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
The form is not validating, but your template is set to always show the same error message about username and password not matching:
The reason it is not validating is probably because you are only using some of the fields from the User object, and a
ModelFormexpects all of the non-editable fields. In the Form’s Meta, setto tell it to only require those fields.
Also note that passwords are not stored in the database as plain text, so creating a user with a password like that will not work. You need to use
user.set_password(form_password).