I'm trying to create a simple form in order to add users. Im using the built in form generation UserCreationForm(). I found example code here that I used.
here is my view:
def user_add(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = User.objects.create_user(**form.cleaned_data)
login(new_user)
return HttpResponseRedirect('main.html')
else:
form = UserCreationForm()
return render(request, 'main/user_add_djDefault.html', {'form': form.as_p()})
The Form is genereated correctly, but when I enter data and submit it then:
Exception Type: TypeError
Exception Value: 'password1' is an invalid keyword argument for this function
the error happens here:
new_user = User.objects.create_user(form.cleaned_data)
Since the form creation and validation is based on the same model I wonder where this error comes from ...
You're getting the error because create_user
expects a parameter called password
and NOT password1
that is used in UserCreationForm
.
Notice the signature for create_user
:
create_user(self, username, email=None, password=None, **extra_fields)
You can try calling the method like this:
cd = form.cleaned_data
User.objects.create_user(
username=cd.get('username'),
password=cd.get('password1'),
)