简体   繁体   English

如何使用 django 正确制作注册视图

[英]How to properly make a signup view with django

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我使用 Django 创建了一个注册视图,但它不起作用,它存储在数据库中,但我无法使用该视图存储的数据登录,而我可以使用我使用 manage.py createsuperuser 创建的用户登录这里是我的注册视图

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.我只需要知道究竟出了什么问题以及如何准确修复它,或者我需要学习什么才能正确执行此任务。

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.但主要问题是您在保存密码之前没有 hash 密码。

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您可以在文档中阅读它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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