python - 如何优雅地实现django的登录/注册?
迷茫
迷茫 2017-04-18 09:45:54
0
2
665

我是看的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('/')

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
黄舟

First of all, when logging in, you must calculate a session or cookies for the front end. After logging in, the front end will come to you with the calculated session or cookies and say that I have logged in. This is my login credentials, and then After the server gets it, it calculates whether it is the same as what I calculated. If it is, it means it is logged in normally. Instead of simply jumping to a page, no information is returned.

It goes without saying that you need to register. . Just write the account password into the database, then use it back when logging in and compare it. If it is correct, jump to login.

Logout is to clear the user's login information, such as cookies, refresh session, etc. If it is not detected, you will not be able to access the login page, so you can just jump and redirect to the login page.

巴扎黑

Should we verify the username and password passed from the front end?

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

Same as registration

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template