Home > Blockchain >  How to properly make a signup view with django
How to properly make a signup view with django

Time:08-12

I'm made a sign up view with Django but it's not working, it's stored in the database and all but I can't login with the data stored by that view while I can login with the user I made with manage.py createsuperuser here's my signup view

def signup(request):
if request.method == 'POST':
    user = User.objects.create(
        username=request.POST['username'],
        password=request.POST['password'],
        email=request.POST['email'],
        first_name=request.POST['first_name'],
        last_name=request.POST['last_name'],
    )
    user.save()
    return HttpResponseRedirect(reverse('posts'))
else:
    signupform = SignUpForm()
    return render(request, 'users/signup.html', {'form': signupform})

and here's my signup form

class SignUpForm(forms.Form):
    
    username = forms.CharField(max_length=30, required=True)
    password = forms.CharField(widget=forms.PasswordInput(), required=True)
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

I just need to know what exactly is wrong and how to fix it exactly or what do I need to learn to perform this task properly.

CodePudding user response:

There are a few things in your code that are not properly done. But the main problem is that you don't hash the password before saving it.

from django.contrib.auth.hashers import make_password,


def signup(request):
    if request.method == 'POST':
        user = User.objects.create(
            username=request.POST['username'],
            password=make_password(request.POST['password']),
            email=request.POST['email'],
            first_name=request.POST['first_name'],
            last_name=request.POST['last_name'],
        )
        return HttpResponseRedirect(reverse('posts'))
    else:
        signupform = SignUpForm()
        return render(request, 'users/signup.html', {'form': signupform})

This code is solve your problem. But if you want to do it more correctly, you should validate the data before saving using the form and save the form, not create a user in the view. You can read about it in the documentation

  • Related