I want to create a user in django but create_user() method doesn't work

Question:

I’m trying to create a user using create_user method but it’s not working and not showing any errors

in my views.py I have the following code

from django.contrib.auth.models import User
from django.views import View
from django.shortcuts import render, redirect
from django.contrib import messages

class Signup(View):
    def get(self, request):
        return render(request, 'myqpp/signup.html')
    def post(self, request):
        username=request.POST.get('username')
        pas = request.POST.get('password')
        email = request.POST.get("email")
        user = User.objects.create_user(username, email, pas)
        user.save()
        return redirect('/signin/')

class Signin(View):
    def get(self, request):
        return render(request, 'myapp/signin.html')
    def post(self, request):
        username = request.POST.get('username')
        pas = request.POST.get('password')

        user = authenticate(username=username, password=pas)

        if user is not None:
            login(request, user)
            print('Success')
            return redirect('/', context={"user":user})
        else:
            print('Failed')
            messages.error(request, 'Bad Credentials')
            return redirect('/signin/')

I always get the message "Bad credentials" and when I review the Users table in django admin/ page it shows that there is no new user added
When I click the submit button on the signup page, console log is like this

[21/Aug/2022 15:31:50] "GET /signup/ HTTP/1.1" 200 3907
Failed

[21/Aug/2022 15:32:07] "POST /signin/ HTTP/1.1" 302 0

[21/Aug/2022 15:32:07] "GET /signin/ HTTP/1.1" 200 3304

I don’t know what is the problem as it’s not showing any errors

This is myqpp/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.MainView.as_view(), name='home'),
    path('signup/', views.Signup.as_view(), name='signup'),
    path('signin/', views.Signin.as_view(), name='signin'),
    path('signout/', views.Signout.as_view(), name='signout'),
]
Asked By: Hosam Hashem

||

Answers:

Seems you have wrong path in action attribute in <form> tag.

[21/Aug/2022 15:31:50] "GET /signup/ HTTP/1.1" 200 3907
Failed

When you submit signup form, you have to call with POST the signup page, not the signin (this can be seen with the ‘Failed’ text in the console).

Answered By: Lorenzo Prodon

You must use creat to create the field, not creat_user! And you must specify the name of each argument. Like this:

user = User.objects.create(username=username, email=email, password=pas)