登录注册功能——Django

一、定义用户模型

  • user/models.py
from django.db import models
from django.contrib.auth.hashers import make_password


class User(models.Model):
    nickname = models.CharField(max_length=64, unique=True, null=False, blank=False)
    password = models.CharField(max_length=64, null=False, blank=False)
    head = models.ImageField()
    age = models.IntegerField()
    sex = models.IntegerField()

    def save(self):
        if not self.password.startswith('pbkdf2_'):
            self.password = make_password(self.password)
        super().save()

二、定义form表单模型

from django.forms import Form, ModelForm, CharField
from django.contrib.auth.hashers import check_password

from user.models import User

#注册表单
class RegisterForm(ModelForm):
    class Meta:
        model = User
        fields = ['nickname', 'password', 'head', 'age', 'sex']


#登录表单
class LoginForm(Form):
    nickname = CharField(max_length=64)
    password = CharField(max_length=64)

    def chk_password(self):
        nickname = self.cleaned_data['nickname']
        password = self.cleaned_data['password']

        try:
            user = User.objects.get(nickname=nickname)
            return user, check_password(password, user.password)
        except:
            return None, False

三、登录注册视图函数

  • user/views.py
from django.shortcuts import render, redirect

from user.forms import RegisterForm, LoginForm

#注册
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST, request.FILES)
        if form.is_valid():
            user = form.save(commit=False)
            user.save()
            request.session['uid'] = user.id
            return redirect('/user/info/')
        else:
            return render(request, 'register.html', {'errors': form.errors})
    return render(request, 'register.html')

#登录
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user, passed = form.chk_password()
            if passed:
                request.session['uid'] = user.id
                return redirect('/user/info/')
        else:
            return render(request, 'login.html', {'errors': form.errors})

    return render(request, 'login.html')

#用户详情
def info(request):
    user = getattr(request, 'user', None)
    if user is None:
        return redirect('/user/login/')
    else:
        return render(request, 'info.html', {'user': user})

#退出登录
def logout(request):
    request.session.flush()
    return redirect('/post/home/')

四、登录验证的中间件

  • user/middleware.py
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin

from user.models import User


class AuthenticationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        uid = request.session.get('uid')
        if uid is not None:
            user = User.objects.get(id=uid)
            request.user = user

五、在配置文件中加入验证中间件

  • setting.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'user.middleware.AuthenticationMiddleware', #登录验证中间件
]

你可能感兴趣的:(Django,登录注册)