I'm setting up user registration with built-in User model and UserCreationForm. Problem is that form validation fails when proper credentials are given. And I can't understand why?
It looks like form.cleaned_data lacks 'password2' for some reason. But form.data has it.
Contents of POST is equal to form.data.
POST
csrfmiddlewaretoken: 1EA7k5HUM7aDO1qj9DPslM18rz2QATZh0qtRd1R8iHc9MmnBgLGyUsO3YJzQjNwA
username: test
password1: qwe
password2: qwe
I have the same code in other project on django==2.1 and there's no problem.
views.py
from django.contrib.auth.forms import UserCreationForm
from django.http import JsonResponse
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
return JsonResponse({'username': username, 'password': password})
else:
return JsonResponse({
'error': 'Form not valid',
'messages': form.error_messages,
'cleaned_data': form.cleaned_data,
'data': form.data,
})
else:
form = UserCreationForm()
return render(request, 'register_form.html', {'form': form.as_p()})
Template :
{% block content %}
<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit" name="" value="Submit">
</form>
{% endblock %}
Expected:
{'username': 'test', 'password': 'qwe'}
Actual:
{"error": "Form not valid",
"messages": {"password_mismatch": "The two password fields didn't match."},
"cleaned_data": {"username": "test",
"password1": "qwe"},
"data": {"csrfmiddlewaretoken": "long string:)",
"username": "test",
"password1": "qwe",
"password2": "qwe"}}