PyCharm实现一个简单的注册登录Django项目

之前已经实现了一个简单的Django项目,今天我们j基于之前的项目来实现注册、登录以及登录成功之后跳转到StuList页面。

1、连接数据库

1.1 配置数据库信息:

首先在myweb的settings.py 文件中设置MySQL数据库连接信息:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your_database_name',
        'USER': 'your_username',
        'PASSWORD': 'your_password',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

2、定义用户模型

在myapp底下的models新增一个stu:
Class Stu

class Stu(models.Model):
    '''自定义Stu表对应的Model类'''
    #定义属性:默认主键自增id字段可不写
    id = models.AutoField("学号",primary_key=True)
    name = models.CharField("姓名",max_length=16)
    age = models.SmallIntegerField("年龄")
    sex = models.CharField("性别",max_length=1)
    classid=models.CharField("班级",max_length=8)

    # 定义默认输出格式
    def __str__(self):
        return "%d:%s:%d:%s:%s"%(self.id,self.name,self.age,self.sex,self.classid)

    # 自定义对应的表名,不设定的话默认表名:myapp_stu
    class Meta:
        db_table="stu"

3、数据迁移-创建数据库表结构

在终端依次执行代码:

python manage.py makemigrations
python manage.py migrate

执行成功之后我们打开mysql查看数据库表,会发现多了很多表以及我们的stu表。
tables

4、创建视图函数

在myapp/views.py中编写处理注册、登录等功能的视图函数:

def register(request):
    '''
    跳转注册
    '''
    return render(request, "register.html")
def update(request):
    '''
    提交注册
    '''

    name = request.POST.get("username")
    passwd = request.POST.get("password")
    check_passwd = request.POST.get("check_password")
    print("name:%s,password:%s" % (name, passwd))
    # 这里的User 调用的是django自带的auth_user 
    # from django.contrib.auth.models import User
    exist = User.objects.filter(username=name)
    if exist:
        return HttpResponse("用户已经存在")

    if passwd != check_passwd:
        return HttpResponse("密码不相同,请重新输入")

    # hash_password = make_password(passwd)
    user = User.objects.create_user(
        username=name,
        password=passwd

    )

    user.save()
    # 注册成功
    return redirect("/login")

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


def dologin(request):
    username = request.POST.get("username")
    password = request.POST.get("password")

    print("username,password", username, password)
    exist = User.objects.filter(username=username).exists()

    if not exist:
        return redirect("/login?error = 用户不存在")

    user = authenticate(username=username, password=password)

    if user:
        # 登录成功 跳转到stulist页面
        return redirect("/stuPage")
    else:
        return redirect("/login?error = 密码错误")

    return redirect("/login")


def stuPage(request):
    stuList = Stu.objects.all()
    paginator = Paginator(stuList, 5)  # 每页显示10个学生
    page = request.GET.get('page', 1)
    try:
        students = paginator.get_page(page)
    except PageNotAnInteger:
        # 如果页码不是整数,返回第一页的数据
        students = paginator.get_page(1)
    except EmptyPage:
        # 如果页码超出范围,返回最后一页的数据
        students = paginator.get_page(paginator.num_pages)
    return render(request, "studentList.html", {"stuList": students})



5、配置URL路由

在myapp/urls.py中配置URL路由:

    # 跳转注册页面
    url(r'^register$', views.register, name='register'),
    # 提交注册api
    url(r'^update$', views.update, name='update'),
    # 跳转登录页面
    url(r'^login$', views.login, name='login'),
    # 提交登录api
    url(r'^dologin$', views.dologin, name='dologin'),
    # 学生list页面
    url(r'^stuPage', views.stuPage, name='stuPage'),

这里值得注意的是,假如你使用的django版本为4.x+,则url就得换为path
写为

    path(r'^stuPage', views.stuPage, name='stuPage'),

引入对应的package即可:from django.urls import path。
urls

6、编写前端页面

6.1 创建模板文件夹:

在你的应用程序目录下创建一个名为templates的文件夹,用于存放HTML模板文件。

6.2 配置模板路径:

在myweb的settings.py 文件中配置模板路径,告诉Django 在哪里查找模板文件。在TEMPLATES 配置中添加应用程序的模板目录路径:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        },
    },
]

6.3 编写HTML

在templates文件夹下分别创建注册、登录、studentList等页面。一下是我的示例代码:
注册:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register Page with Particle Background</title>
<style>
    body {
        margin: 0;
        padding: 0;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        background-color: #000;
    }

    canvas {
        position: fixed;
        top: 0;
        left: 0;
        z-index: -1;
    }

    #edit-area {
        width: 25%;
        margin: 0 auto;
        margin-top: 100px;
        padding: 20px;
        border-radius: 8px;
        background-color: rgba(255, 255, 255, 0.8);
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    h3 {
        text-align: center;
        margin-bottom: 20px;
    }

    form {
        display: flex;
        flex-direction: column;
    }

    label {
        margin-bottom: 10px;
    }

    input {
        padding: 10px;
        border-radius: 5px;
        border: 1px solid #ccc;
        margin-bottom: 10px;
    }

    button {
        padding: 10px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }

</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="edit-area">
    <h3>新用户注册</h3>
    <form action="{% url 'update' %}" enctype="multipart/form-data" method="post">
        {% csrf_token %}

        <label for="username">用户名:</label>
        <input type="text" name="username" id="username" required>

        <label for="password">密码:</label>
        <input type="password" name="password" id="password" required>

        <label for="check_password">确认密码:</label>
        <input type="password" name="check_password" id="check_password" required>

        <button type="submit">注册</button>
    </form>
<!--	 <button οnclick="location.href='{% url 'login' %}'">Go to Login</button>-->
</div>

<script>


    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    let particlesArray;


    function createParticle() {
        particlesArray = [];
        const numberOfParticles = canvas.width * canvas.height / 9000;

        for (let i = 0; i < numberOfParticles; i++) {
            particlesArray.push({
                x: Math.random() * canvas.width,
                y: Math.random() * canvas.height,
                size: Math.random() * 3 + 1,
                speedX: Math.random() * 3 - 1.5,
                speedY: Math.random() * 3 - 1.5
            });
        }
    }


    function drawParticles() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        for (let i = 0; i < particlesArray.length; i++) {
            const item = particlesArray[i];
            ctx.fillStyle = 'white';
            ctx.beginPath();
            ctx.arc(item.x, item.y, item.size, 0, Math.PI * 2);
            ctx.fill();

            item.x += item.speedX;
            item.y += item.speedY;

            if (item.x < 0 || item.x > canvas.width) {
                item.speedX = -item.speedX;
            }
            if (item.y < 0 || item.y > canvas.height) {
                item.speedY = -item.speedY;
            }
        }
    }


    function animate() {
        requestAnimationFrame(animate);
        drawParticles();
    }

    createParticle();
    animate();
</script>
</body>
</html>

登录:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page with 3D Background</title>
<style>
    body {
        margin: 0;
        padding: 0;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        perspective: 1000px;
        background: linear-gradient(45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
        background-size: 400% 400%;
        animation: gradient 15s ease infinite;
    }

    @keyframes gradient {
        0% {
            background-position: 0% 50%;
        }
        50% {
            background-position: 100% 50%;
        }
        100% {
            background-position: 0% 50%;
        }
    }

    .login-container {
        width: 25%;
        margin: 0 auto;
        margin-top: 100px;
        padding: 2%;
        border: 1px solid #cccccc;
        border-radius: 8px;
        background-color: rgba(255, 255, 255, 0.8);
        position: relative;
        z-index: 1;
    }

    input {
        display: block;
        width: 100%;
        margin-bottom: 10px;
        padding: 5px;
        border-radius: 3px;
        border: 1px solid #ccc;
    }

    #submit {
        width: 100%;
        padding: 10px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }
</style>
</head>
<body>
<div class="login-container">
    <h3 style="text-align:center;">用户登录</h3>
    <form action="{% url 'dologin' %}" enctype="multipart/form-data" method="post">
        {% csrf_token %}
        <input type="text" name="username" placeholder="用户名" required />
        <input type="password" name="password" placeholder="密码" required />
        <input id="submit" type="submit" value="Login"/>
    </form>
	 <button onclick="location.href='{% url 'register' %}'">Go to Register</button>
</div>
</body>
</html>

学生列表:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生列表</title>
    <!-- 引入Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .container {
            margin-top: 50px;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        table {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        th, td {
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <h1 class="my-4">学生列表</h1>
    <table class="table table-striped table-hover">
        <thead>
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>班级</th>
        </tr>
        </thead>
        <tbody>
        {% for student in stuList %}
        <tr>
            <td>{{ student.id }}</td>
            <td>{{ student.name }}</td>
            <td>{{ student.age }}</td>
            <td>{{ student.sex }}</td>
            <td>{{ student.classid }}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
            {% if stuList.has_previous %}
            <li class="page-item"><a class="page-link" href="?page={{ stuList.previous_page_number }}">上一页</a></li>
            {% else %}
            <li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>
            {% endif %}
            {% for i in stuList.paginator.page_range %}
            {% if stuList.number == i %}
            <li class="page-item active"><a class="page-link" href="#">{{ i }} <span
                    class="sr-only">(current)</span></a></li>
            {% else %}
            <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
            {% endif %}
            {% endfor %}
            {% if stuList.has_next %}
            <li class="page-item"><a class="page-link" href="?page={{ stuList.next_page_number }}">下一页</a></li>
            {% else %}
            <li class="page-item disabled"><a class="page-link" href="#">下一页</a></li>
            {% endif %}
        </ul>
    </nav>

</div>
<!-- 引入Bootstrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.min.js"></script>
</body>
</html>

6.4 模板语法简单介绍

在上面的html页面的表单提交用到了如下的代码:

<form action="{% url 'dologin' %}" enctype="multipart/form-data" method="post">

{% url ‘dologin’ %}:
这个模板标签用于生成URL 地址,其中’dologin’是指向一个视图函数的名称或者URL模式的名称。
Django 将根据给定的名称查找对应的URL 地址,并生成完整的URL 地址。
这样做的好处是,当你需要更改URL 地址时,只需更新URL 配置而不必在所有模板中手动修改URL 地址。

7、启动项目

控制台输入:

python manage.py runserver

8、效果展示

首页:
index
登录:
login

注册:
注册
学生列表:
stupage

OK,到这里就完成了一个简单的登录注册项目。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/465075.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

在线疫苗预约小程序|基于微信小程序的在线疫苗预约小程序设计与实现(源码+数据库+文档)

在线疫苗预约小程序目录 目录 基于微信小程序的在线疫苗预约小程序设计与实现 一、前言 二、系统设计 三、系统功能设计 1、疫苗管理 2、疫苗订单管理 3、论坛管理 4、公告管理 四、数据库设计 五、核心代码 六、论文参考 七、最新计算机毕设选题推荐 八、源…

html5cssjs代码 022 表单输入类型示例

html5&css&js代码 022 表单输入类型示例 一、代码二、解释 这段HTML代码定义了一个网页&#xff0c;展示了表单输入类型示例。 一、代码 <!DOCTYPE html> <html lang"zh-cn"> <head><title>编程笔记 html5&css&js 表单输入…

SpringBoot整合JPA

一 运行效果如下 二 项目结构图 三 代码 pom.xml <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance&qu…

2024 年(第 12 届)“泰迪杯”数据挖掘挑战赛——A 题:生产线的故障自动识别与人员配置具体思路以及源代码分析

一、问题背景 随着新兴信息技术的大规模应用&#xff0c;工业生产线的智能化控制技术日益成熟。自动生产线 可以自动完成物品传送、物料填装、产品包装和质量检测等过程&#xff0c;极大地提高了生产效率和 产品质量&#xff0c;减少了生产成本。自动生产线融入故障智能报警…

【Spring Boot 源码学习】深入应用上下文初始化器实现

《Spring Boot 源码学习系列》 深入应用上下文初始化器实现 一、引言二、往期内容三、主要内容3.1 spring-boot 子模块中内置的实现类3.1.1 ConfigurationWarningsApplicationContextInitializer3.1.2 ContextIdApplicationContextInitializer3.1.3 DelegatingApplicationConte…

FFmpeg-aac、h264封装flv及时间转换

文章目录 时间概念流程api核心代码 时间概念 dts: 解码时间戳, 表示压缩帧的解码时间 pts: 显示时间戳, 表示将压缩帧解码后得到的原始帧的显示时间 时间基: time_base &#xff0c; 通常以ms为单位 时间戳: timestamp , 多少个时间基 真实时间&#xff1a;time_base * timest…

email + celery+django 异步发送邮件功能的实现

主要流程&#xff1a; django通过发件服务器到收件服务器&#xff0c;最后到收件人 邮件配置设置需要打开SMTP/IMAP并获的授权码&#xff0c;完成授权功能实现发送给收件人 邮件配置请参考另一博客https://blog.csdn.net/qq_44238024/article/details/136277821 项目结构树…

mac下Appuim环境安装

参考资料 Mac安装Appium_mac电脑安装appium-CSDN博客 安卓测试工具&#xff1a;Appium 环境安装&#xff08;mac版本&#xff09;_安卓自动化测试mac环境搭建-CSDN博客 1. 基本环境依赖 1 node.js 2 JDK&#xff08;Java JDK&#xff09; 3 Android SDK 4 Appium&#x…

数据分析 | Matplotlib

Matplotlib 是 Python 中常用的 2D 绘图库&#xff0c;它能轻松地将数据进行可视化&#xff0c;作出精美的图表。 绘制折线图&#xff1a; import matplotlib.pyplot as plt #时间 x[周一,周二,周三,周四,周五,周六,周日] #能量值 y[61,72,66,79,80,88,85] # 用来设置字体样式…

Linux进程管理:(六)SMP负载均衡

文章说明&#xff1a; Linux内核版本&#xff1a;5.0 架构&#xff1a;ARM64 参考资料及图片来源&#xff1a;《奔跑吧Linux内核》 Linux 5.0内核源码注释仓库地址&#xff1a; zhangzihengya/LinuxSourceCode_v5.0_study (github.com) 1. 前置知识 1.1 CPU管理位图 内核…

如何用Selenium通过Xpath,精准定位到“多个相同属性值以及多个相同元素”中的目标属性值

前言 本文是该专栏的第21篇,后面会持续分享python爬虫干货知识,记得关注。 相信很多同学,都有使用selenium来写爬虫项目或者自动化页面操作项目。同样,也相信很多同学在使用selenium来定位目标元素的时候,或多或少遇见到这样的情况,就是用Xpath定位目标元素的时候,页面…

Mysql主从之keepalive+MySQL高可用

一、Keepalived概述 keepalived 是集群管理中保证集群高可用的一个服务软件&#xff0c;用来防止单点故障。 keepalived 是以VRRP 协议为实现基础的&#xff0c;VRRP 全称VirtualRouter Redundancy Protocol&#xff0c;即虚拟路由冗余协议。虚拟路由冗余协议&#xff0c;可以…

launchctl及其配置、使用、示例

文章目录 launchctl 是什么Unix / Linux类似的工具有什么哪个更常用配置使用常用子命令示例加载一个 launch agent:卸载一个 launch daemon:列出所有已加载的服务:启动一个服务:停止一个服务:禁用一个服务:启用一个服务: 附com.example.myagent.plist内容有趣的例子参考 launch…

力扣L15--- 67.二进制求和(JAVA版)-2024年3月17日

1.题目描述 2.知识点 注1&#xff1a; 二进制用 %2 /2 3.思路和例子 采用竖位相加的方法 4.代码实现 class Solution {public String addBinary(String a, String b) {StringBuilder sbnew StringBuilder();int ia.length()-1;int jb.length()-1;int jinwei0;int digit1,d…

快速排序(数据结构)

1. 前言&#xff1a; 这两种排序经常使用&#xff0c;且在算法题中经常遇见。 这里我们简单分析讨论一下。 1. 快速排序 平均时间复杂度&#xff1a;O&#xff08;nlogn&#xff09; 最坏时间复杂度&#xff1a; O&#xff08;n^2&#xff09; 1.1. 左右向中遍历: 取最右侧4…

Multiplicity - 用一个键盘和鼠标控制多台电脑

Multiplicity 是一款用于多台电脑间控制的软件。通过这个工具&#xff0c;用户可以轻松地在多个计算机之间共享剪贴板、鼠标、键盘和显示屏幕。这样&#xff0c;无需每台电脑之间频繁切换&#xff0c;工作效率也会大大提高。 特征 远程PC访问 无缝控制过渡 兼容所有显示类型…

【Linux杂货铺】进程的基本概念

目录 &#x1f308;前言&#x1f308; &#x1f4c1;进程的概念 &#x1f4c2;描述进程-PCB &#x1f4c2; 查看进程 &#x1f4c2; 查看正在运行的程序 &#x1f4c2;杀死进程 &#x1f4c2;通过系统调用获取进程标识符 &#x1f4c2;通过系统调用创建进程 &#x1f…

万界星空科技商业开源MES,技术支持+项目合作

商业开源的一套超有价值的JAVA制造执行MES系统源码 亲测 带本地部署搭建教程 教你如何在本地运行运行起来。 开发环境&#xff1a;jdk11tomcatmysql8springbootmaven 可以免费使用&#xff0c;需要源码价格便宜&#xff0c;私信我获取。 一、系统概述&#xff1a; MES制造执…

机器学习(26)回顾gan+文献阅读

文章目录 摘要Abstract一、李宏毅机器学习——GAN1. Introduce1.1 Network as Generator1.2 Why distribution 2. Generative Adversarial Network2.1 Unconditional generation2.2 Basic idea of GAN 二、文献阅读1. 题目2. abstract3. 网络架构3.1 Theoretical Results 4. 文…

学习数据结构和算法的第16天

单链表的实现 链表的基本结构 #pragma once #include<stdio.h> #include<stlib.h> typedf int SLTDataType; typedy struct SListNode {SLTDataType data;struct SListNode*next; }SLTNode;void Slisprint(SLTNode*phead); void SListPushBack(SLTNode**pphead,S…