如何优雅地实现django的登录/注册?

kjhlafa
  • 443

我是看的Django Book的教程,然后用最原始的方式实现的。请问关于登录和注册,Django有没有封装像ListView, DetailView, FormView这样的class来直接实现呢?


这是login代码的实现

def user_login(request):
    if request.POST:
        username = password = ''
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
            return redirect('/')
    else:
        context = {}
        return render(request, 'account/login.html', context)

这是register代码的实现 

def user_register(request):
    if request.method == "POST":
        register_form = UserForm(request.POST)
        if register_form.is_valid():
            username = register_form.cleaned_data['username']
            password = register_form.cleaned_data['password']
            email = register_form.cleaned_data['email']

            user = User.objects.create_user(username, email, password)
            user.save()

            login(request, authenticate(username=username, password=password))
            return redirect('/')
    else:
        register_form = UserForm()
        context = {'register_form': register_form}
        return render(request, 'account/register.html', context)

这是logout代码的实现

def user_logout(request):
    logout(request)
    return redirect('/')

一般在实际开发过程中会采用什么方法实现登录/注册/登出呢?

回复
阅读 8.7k
2 个回答
✓ 已被采纳

首先登陆你肯定要算一个session或者cookies给前端,这样在登陆之后,以后前端就会拿着这个算好的session或者cookies上来找你,说我已经登陆了,这是我登陆的凭据,然后服务器端在拿到之后,计算一下是不是跟我算出来的一样,如果是说明是正常登陆了。而不是 简单的跳转一个页面,什么也信息也不回传。

注册这个不用说了吧。。就是往数据库里面写账号密码,然后用回登陆的时候然后比对,正确了就跳转登陆。

登出就是清理掉该用户的登陆信息,比如cookies刷新session啥的,检测不到了之后就会不能访问登陆后的页面了就跳转重定向到登陆页面就可以了。

是不是应该验证从前端传过来的用户名和密码呢?

class LoginForm(forms.Form):

    email = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)
    
    def __init__(self, *args, **kwargs):
        self.user_cache = None
        super(LoginForm, self).__init__(*args, **kwargs)

    def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')

        if email and password:
            if not AtUser.objects.filter(email=email).exists():
                raise forms.ValidationError(u'该账号不存在')

            self.user_cache = authenticate(email=email, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(u'邮箱或密码错误!')

            elif not self.user_cache.is_active:
                raise forms.ValidationError(u'该帐号已被禁用!')

        return self.cleaned_data

    def get_user_id(self):
        """获取用户id"""
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        """获取用户实例"""
        return self.user_cache

注册同理

宣传栏