Django 内置权限实现注册登录教程

2023-03-1717:34:57后端程序开发Comments794 views字数 4449阅读模式

内置权限实现注册登录文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

环境搭建

安装依赖

pip install django

创建项目

# 创建项目
django-admin startproject z07_django_auth

# 创建静态目录和模板目录
cd z07_django_auth
mkdir static templates media

# 创建应用
python manage.py startapp index

配置项目

配置应用:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

# 应用配置
INSTALLED_APPS = [
    # 后台应用
    'django.contrib.admin',
    # 权限应用
    'django.contrib.auth',
    'django.contrib.contenttypes',
    # session应用,用来记录session
    'django.contrib.sessions',
    # message应用,用来发送消息
    'django.contrib.messages',
    # 静态文件应用,用来处理静态文件
    'django.contrib.staticfiles',
    # 入口应用
    'index',
]

配置模板目录:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

# 模板配置
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 配置模板目录
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

配置数据库:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

# 数据库信息
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_shop',  # 数据库名
        'USER': 'root',  # 用户名
        'PASSWORD': 'root',  # 密码
        'HOST': '192.168.33.12',  # 主机
        'PORT': '3306',
        # 取消外键约束,否则多对多模型迁移报django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')
        'OPTIONS': {
            "init_command": "SET foreign_key_checks = 0;",
            'charset': 'utf8'
        },
    }
}

引入MySQL驱动:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

import zdppy_mysql

zdppy_mysql.install_as_MySQLdb()

执行数据库迁移:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

python manage.py makemigrations
python manage.py migrate

配置语言和时区:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

# 时区配置
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True

配置静态目录:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

# 文件配置
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_URL = '/static/'
if not DEBUG:
    STATIC_ROOT = BASE_DIR / 'static'
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

日志配置:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

# 配置日志
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    # 日志处理器
    'handlers': {
        # 控制台日志处理器
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        # SQL语句输出到控制台
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'DEBUG',
        },
    }
}

总路由

from django.contrib import admin
from django.urls import path, include, re_path
from django.views.static import serve

from . import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("index.urls")),
    # 配置媒体文件目录
    re_path('^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT})
]

子路由

from django.urls import path

from . import views

app_name = 'index'
urlpatterns = [
    path('', views.index, name='index'),
]

视图函数

from django.shortcuts import render


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

模板

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Django权限示例</title>
</head>
<body>
<h1>Django权限示例</h1>
<h2>路由列表</h2>
<ul>
    <li><a href="{%%20url%20'index:index'%20%}">/</a></li>
</ul>
</body>
</html>

启动测试

在项目目录执行以下命令启动服务:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

python manage.py runserver

用户注册

路由设计

from django.urls import path

from . import views

app_name = 'index'

urlpatterns = [
    # 用户注册
    path('/register/', views.register, name='register'),
]

视图函数

from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.urls import reverse

def register(request):
    """用户注册"""
    # 渲染注册页面
    if request.method == "GET":
        return render(request, 'register.html')

    # 执行注册功能
    if request.method == "POST":
        # 获取用户名和密码
        uname = request.POST.get("username", '')
        pwd = request.POST.get("password", '')
        email = request.POST.get("email", '')
        re_password = request.POST.get("re-password", '')
        if pwd != re_password:
            info = "两次密码不一致"
        elif User.objects.filter(username=uname):
            info = '用户已经存在'
        else:
            # 添加用户数据到数据库
            # is_staff:是否登录后台
            # is_active:是否激活
            # is_superuser:是否为超级管理员
            d = dict(username=uname, password=pwd, email=email, is_staff=1, is_active=1, is_superuser=1)
            user = User.objects.create_user(**d)
            info = '注册成功,请登陆'
            # 跳转到登陆页面
            return redirect(reverse("index:login"))
        return render(request, 'register.html', {"info": info})

模板:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>用户注册</title>
</head>
<body class="hold-transition register-page">
<div class="register-box">
    <div class="register-logo">
        <b>用户注册</b>
    </div>
    <div class="card">
        <div class="card-body register-card-body">
            <form action="{% url 'index:register' %}" method="post">
                {% csrf_token %}
                <div class="input-group mb-3">
                    <input type="text" class="form-control" name="username" placeholder="用户名">
                </div>
                <div class="input-group mb-3">
                    <input type="email" class="form-control" name="email" placeholder="邮箱">
                </div>
                <div class="input-group mb-3">
                    <input type="password" class="form-control" name="password" placeholder="密码">
                </div>
                <div class="input-group mb-3">
                    <input type="password" class="form-control" name="re-password" placeholder="重复密码">
                </div>
                <div class="row">
                    <div class="col-8">
                        <label for="agreeTerms">
                            {{ info }}
                        </label>
                    </div>
                    <div class="col-4">
                        <button type="submit" class="btn btn-primary btn-block">注册</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

测试地址:http://192.168.33.13:8000/reigister/文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/31477.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/31477.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定