I'm Creating Login & Register Form In Django. I got an error create() takes 1 positional argument but 5 were given
.
code:
def register(request):
if request.method=="POST":
username=request.POST['username']
name=request.POST['name']
email=request.POST['email']
password=request.POST['password']
user_create = User.objects.create(username,name,email,password)
user_create.save()
messages.success(request, " Your account has been successfully created")
return redirect("/")
else:
return HttpResponse("404 - Not found")
html
https://paste.pythondiscord.com/amoturoqop.xml
CodePudding user response:
Try this:
def register(request):
if request.method=="POST":
username=request.POST['username']
name=request.POST['name']
email=request.POST['email']
password=request.POST['password']
instance, created = User.objects.update_or_create(
username=username,
defaults={'username': username, 'name': name, 'email': email, 'password': password},
)
if created:
messages.success(request, " Your account has been successfully created")
else:
messages.success(request, " Your account has been successfully updated")
return redirect("/")
else:
return HttpResponse("404 - Not found")
Explanation:
As you face UNIQUE constraint failed: auth_user.username
issue so update_or_create
will resolve your that. It will update the data if any existing one found else it will create it.
If User exists with
username=username
then update values with defaults, else create new User with defaults values
CodePudding user response:
You should work with .create_user(…)
[Django-doc] and work with named parameters, not positional ones:
user_create = User.objects.create_user(
username=username,
first_name=name,
email=email,
password=password
)
The .create_user(…)
function will hash the password such that the user can be authenticated properly.
While the first three parameters are username
, email
and password
and you thus can pass these as positional parameter, I would advise against that since explicit is better than implicit (part of The Zen of Python).
Since .create_user(…)
will save the object in the database, you do not have to .save()
the user_create
:
def register(request):
if request.method == 'POST':
username=request.POST['username']
name=request.POST['name']
email=request.POST['email']
password=request.POST['password']
User.objects.create_user(
username=username,
first_name=name,
email=email,
password=password
)
messages.success(request, 'Your account has been successfully created')
return redirect('/')
else:
return HttpResponse('404 - Not found', status=404)