Python Django实践项目--用户登录登出

Python Django实践项目–用户登录登出

版本信息

  • python 2.7.10
  • Django 1.11.25

实现介绍

利用django自带的Model User保存用户信息,django.contrib.auth 的login 和 logout用于session的登入登出, authenticate用于验证用户信息。

项目源码

https://github.com/cui134/Django-Login

效果图

Python Django实践项目--用户登录登出_第1张图片Python Django实践项目--用户登录登出_第2张图片

实现步骤

创建项目

打开终端,输入

django-admin startproject login

设置语言,时区

进入login/setting.py,修改部分代码

LANGUAGE_CODE = 'zh-hans' 
TIME_ZONE = 'Asia/Shanghai'  

创建数据模型

创建login/models.py

# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
class BaseModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class UserInfo(BaseModel):
    gender = (
        ('male', "男"),
        ('female', "女"),
    )

    user = models.OneToOneField(User)
    sex = models.CharField(max_length=32, choices=gender, default="男")
    def __str__(self):
        # 使用__str__方法帮助人性化显示对象信息;
        return self.user.username
    class Meta:
        db_table = "user_info"
        ordering = ["-created_at"]
        verbose_name = "用户"
        verbose_name_plural = "用户"

    @classmethod
    def get_user_by_auth_user_id(cls, _id):
        user = cls.objects.filter(user__id=_id)
        if user.exists():
            return user.first()
        return None

设置数据库

进入login/setting.py, 这里没有改动,默认使用sqlite

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

注册APP login

进入login/setting.py, 加上login

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'login',
]

初始化数据库,创建数据库和表

打开终端,输入下面两条命令

python manage.py makemigrations login
python manage.py migrate

在Admin中注册模型

进入login/admin.py

from django.contrib import admin

# Register your models here.

from . import models

admin.site.register(models.UserInfo)

代码实现

后台

login/urls.py

from django.conf.urls import url
from django.contrib import admin
from login import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.IndexView.as_view()),
    url(r'^login/', views.LoginView),
    url(r'^logout/', views.LogoutView.as_view()),
]

login/utils/BaseView

from django.views.generic.base import View
from django.shortcuts import redirect
class AuthenticateView(View):

    @staticmethod
    def http_unauthorized(request, *args, **kwargs):
        return redirect('/login/')

    def dispatch(self, request, *args, **kwargs):

        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(),
                              self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        # 使用Django自带的User进行用户验证
        if request.user.is_authenticated:
            from login.models import UserInfo
            user = UserInfo.get_user_by_auth_user_id(request.user.id)
            if user is None:
                handler = self.http_unauthorized
            else:
                request.user_info = user
        else:
            handler = self.http_unauthorized
        return handler(request, *args, **kwargs)

login/views.py

# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib.auth import login, logout, authenticate
from . import models
from . import forms
from login.utils.BaseView import AuthenticateView
# Create your views here.

class IndexView(AuthenticateView):
    def get(self, request):
        return render(request, 'login/index.html')


def LoginView(request):
    print "login request user:", request.user
    if request.user.is_authenticated:
        return redirect('/index/')

    if request.method == 'POST':
        login_form = forms.UserForm(request.POST)
        message = '请检查填写的内容!'
        
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')

            auth_user = authenticate(request, username=username, password=password)
            if auth_user:
                print "auth_user:", auth_user.username
                login(request, auth_user)
                return redirect('/index/')
            else:
                message = '密码不正确或者用户不存在!'
                return render(request, 'login/login.html', locals())
        else:
            return render(request, 'login/login.html', locals())

    login_form = forms.UserForm()
    return render(request, 'login/login.html', locals())

class LogoutView(AuthenticateView):
    def get(self, request):
        logout(request)
        return redirect("/login/")

login/forms.py

# -*- coding: utf-8 -*-
from django import forms

class UserForm(forms.Form):
    username = forms.CharField(label="用户名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': "Username",'autofocus': ''}))
    password = forms.CharField(label="密码", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder': "Password"}))

前端html页面

login/templates/login/index.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页title>
head>
<body>
<h1>{{ request.session.user_name }}!  欢迎回来!h1>
<p>
    <a href="/logout/">登出a>
p>
body>
html>

login/templates/login/login.html


<html lang="en">
  <head>
    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <title>登录title>
  head>
  <body>
    <div class="container">
            <div class="col">
                <form class="form-login" action="/login/" method="post">
                    {% if message %}
                        <div class="alert alert-warning">{{ message }}div>
                    {% endif %}
                    {% csrf_token %}
                    <h3 class="text-center">欢迎登录h3>
    
                    <div class="form-group">
                        {{ login_form.username.label_tag }}
                        {{ login_form.username}}
                    div>
                    <div class="form-group">
                        {{ login_form.password.label_tag }}
                        {{ login_form.password }}
                    div>
    
                    <div>
                        <a href="/register/" class="text-success " ><ins>新用户注册ins>a>
                        <button type="submit" class="btn btn-primary float-right">登录button>
                    div>
                    form>
            div>
    div> 

    
    
   
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js">script>
    <script src="https://cdn.bootcss.com/popper.js/1.15.0/umd/popper.js">script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js">script>

  body>
html>

创建超级管理员

打开终端,输入下面命令,根据提示完成创建

python manage.py createsuperuser

启动服务

打开终端,输入下面命令

python manage.py runserver

创建用户,用于登录实验

打开http://127.0.0.1:8000/admin/, 先用superuser账户进行登录,创建新的用户用于登录页面的登录

登录

  • 打开http://127.0.0.1:8000/index/ 会跳转http://127.0.0.1:8000/login/请求登录
  • 打开http://127.0.0.1:8000/login/, 用上一步创建的用户进行登录,点击登录,页面会跳转至http://127.0.0.1:8000/index/
  • 点击登出,会跳回http://127.0.0.1:8000/login/

你可能感兴趣的:(python学习,django,python,登录,实践)