简体   繁体   中英

Django: Create new user account

I'm having some trouble creating a new account and then logging in. I enter all the credentials in (first_name, last_name, username, password), and select "Create new account", and it successfully redirects me back to the login page. However, when I try to login with this new account, it says that my username doesn't exist.

The problem is most likely in my views.py file:

def create_account(request):
    if request.method == 'POST':
        new_user = User(username = request.POST["username"], 
                        password = request.POST["password"])
        new_user.save()
        Student.objects.create(user=new_user, 
                               first_name=str(request.POST.get("first_name")),
                               last_name=str(request.POST.get("last_name")))
        new_user.is_active = True
        return redirect('../')
    else:
        return render(request, 'polls/create_account.html')

Let me know if you guys need any more code or information. Thanks!

The password field needs to be encrypted. If you are going to set the password, you need to use set_password() method that will deal with encryption.

new_user = User(username = request.POST["username"])
        new_user.set_password(request.POST["password"])
        new_user.save()

this another option if you work in form with cleaned_data :

def create_account(self, request):
    if request.method == 'POST':
        form  = RegisterForm(request.POST) #registration form
        if form.is_valid():
            cd              = form.cleaned_data
            username        = cd['username']
            password        = cd['password']

            new_user = User.objects.create_user(
                            username = cd['username'],
                            password = cd['password']
                        )
            new_user.save()

            #... do stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM