Django(四)注册登录注销

django自带的user表的所有字段

  1. id int(11) 用户id
  2. password varchar(128) 用户密码
  3. last_login datetime 最后登录的日期时间
  4. is_superuser tinyint(1) 是否是超级用户
  5. username varchar(30) 用户名
  6. first_name varchar(30) 名字(外国人设计的框架所以他是有名字和姓氏的)
  7. last_name varchar(30) 姓氏(外国人设计的框架所以他是有名字和姓氏的)
  8. email varchar(254) 邮箱地址
  9. is_staff tinyint(1) 职员状态,指明用户是否可以登录到这个管理站点。
  10. is_active tinyint(1) 指明用户是否被认为活跃的。以反选代替删除帐号。
  11. date_joined datetime 加入日期

python manage.py shell 进入django的终端:

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('test','924632889@qq.com','nihao')  
>>> user.last_name='Lean'
>>> from django.contrib.auth.hashers import make_password
>>> user.password = make_password('123')
>>> user.save()

你就可以在django的admin后台可以看到这个新建的用户了,首先你要先登录超级管理员用户,授予你新建的这个用户权限才可以登陆到后台。

创建超级用户

>>> python manage.py createsuperuser 

登录注册注销方法一

方法一用的django的form类,和django自带的User

views.py

# coding:utf-8
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect, HttpResponse
from app.form import UserForm, LoginForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib import auth

# Create your views here.


def index(request):
    return render(request, 'index.html')

@csrf_exempt
def register(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST)
        if user_form.is_valid():
            username = user_form.cleaned_data['username']
            password = user_form.cleaned_data['password']
            email = user_form.cleaned_data['email']
            if User.objects.filter(username=username):
                return HttpResponse('<h1>此用户名已被注册</h1>')
            else:
                user = User.objects.create_user(username, email, password)
                user.is_superuser = True
                user.is_staff = True
                user.save()
                user = authenticate(username=username, password=password)
                auth.login(request, user)
                return render(request, 'index.html')
        else:
            return render(request, 'failure.html', {'reason': user_form.errors})
    else:
        user_form = UserForm()
    return render(request, 'register.html', {'form': user_form})


@csrf_exempt
def login(request):
    form = LoginForm()
    if request.method == 'POST':
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if User.objects.filter(username=username):
                if user is not None:
                    auth.login(request, user)
                    response = render(request, 'index.html', {'form': login_form})
                    # 将username写入浏览器cookie,失效时间为3600
                    response.set_cookie('username', username, 3600)
                    return response
            else:
                # 比较失败,还在login
                return render(request, 'login.html', {'form': form})
        else:
            return render(request, 'login.html', {'form': form})
    return render(request, 'login.html', {'form': form})


def logout_view(request):
    auth.logout(request)
    return render(request, 'index.html', locals())

form.py

from django import forms


class UserForm(forms.Form):
    username = forms.CharField(max_length=50, widget=forms.TextInput())
    email = forms.EmailField(max_length=50, widget=forms.TextInput())
    password = forms.CharField(max_length=50, widget=forms.PasswordInput())


class LoginForm(forms.Form):
    username = forms.CharField(max_length=50, widget=forms.TextInput())
    password = forms.CharField(max_length=50, widget=forms.PasswordInput())

urls.py

from app.views import *
from django.conf.urls import include, url
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', index),
    url(r'^register$', register),
    url(r'^login$', login),
    url(r'^logout$', logout_view)
]

index.html

login.html

failure.html

register.html

登录注册注销方法二

方法二是用models.py 建立了User表,以request请求的方式做登录,后端视图层对登录密码进行加密,登录的操作是对session进行操作。

views.py

# coding:utf-8
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect, HttpResponse
from models import User
import hashlib
# from django.contrib.auth import authenticate, login, logout


def index(request):
    return render(request, 'index.html')


def register_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        if User.objects.filter(username=username):
            return HttpResponse('<h1>用户已存在!</h1>')
        else:
            password = add_password(request.POST['password'])
            email = request.POST['email']
            phone = request.POST['phone']
            user = User.objects.create(
                username=username, password=password, email=email, phone=phone)
            request.session["username"] = user.username
            return redirect('/')

    return render(request, 'register.html', locals())


@csrf_exempt
def login_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = add_password(request.POST['password'])
        user_objs = User.objects.filter(username=username)
        if len(user_objs) == 1:
            user = user_objs[0]
            request.session["username"] = user.username
            return redirect('/')
        else:
            return HttpResponse('<h1>用户不存在或者密码账号输入不正确</h1>')
    else:
        return render(request, 'login.html', locals())
    return render(request, 'index.html', locals())


def logout_view(request):
    del request.session
    return render(request, 'index.html', locals())


def add_password(password):
    m = hashlib.md5(password).hexdigest()
    return m

urls.py

from app.views import *
from django.conf.urls import include, url
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', index),
    url(r'^register$', register_view),
    url(r'^login$', login_view),
    url(r'^logout$', logout_view)
]

models.py

# coding:utf-8
from django.db import models
# Create your models here.


class User(models.Model):
    username = models.CharField(unique=True, max_length=50)
    password = models.CharField(max_length=30)
    email = models.EmailField()
    datetime = models.DateTimeField(auto_now_add=True)
    phone = models.CharField(max_length=30)
    image = models.ImageField(null=False, blank=True)

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        ordering = ['-id']

    def __unicode__(self):
        return self.username

admin.py

from django.contrib import admin
from models import User
# Register your models here.
admin.site.register(User)

index.html

login.html

register.html

登录注册注销方法三

第三种方式其实跟第二种差不多,在models.py建立User表,去继承django自带的User表,用再自己加自己想要加的字段,等于是用户名密码的加密走django自带的,登录注册注销也用django自带的方法,一般不大的项目有这种方式的比较多,大项目一般用第二种的比较多。擦,终于写完了!


热评文章