41.登录注册小案例实现——准备阶段

241 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

登录注册案例

1.登录注册第一步——创建模型生成数据表:

(1)名为mucis的app下的models.py文件中创建:

from django.db import models

# Create your models here.

class User(models.Model):
    username = models.CharField(max_length=30, unique=True)
    password = models.CharField(max_length=50)

(2)执行映射文件生成数据表:

在这里插入图片描述 在这里插入图片描述

2.基本框架的搭建

(1)登录注册登出视图函数框架编写:

(mucis/views.py文件~)

from django.views import View			#使用类视图,要导入!

class LoginResponse(View):
    def get(self,request):
        return "登录页面"
    def post(self):
        """
        登录逻辑
        :return:
        """
        pass

class RegisterResponse(View):
    def get(self, request):
        return "注册页面"
    def post(self):
        """
        注册逻辑
        :return:
        """
        pass
"""
微信公众号:孤寒者
欢迎关注,持续分享干货文章~
如有问题也可关注微信公众号咨询哦!
"""
def logout(request):
    """
    退出登录
    :param request:
    :return:
    """
    pass    

(2)登录注册登出路径配置:

(mucis/urls.py文件~)

from django.urls import path

from mucis import views

urlpatterns = [
    path('login/', views.LoginResponse.as_view(), name="login"),   # 登录
    path('register/', views.RegisterResponse.as_view(), name="register"),   # 注册
    path('logout/', views.logout, name="logout"),   # 退出
]

(2)登录注册登出前端模板框架编写:

(templates/mucis/login.html文件~)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
    <form action="" method="post">
        {% csrf_token %}
        <h2>登录</h2>
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <button type="submit">登录</button>
    </form>
</body>
</html>

(templates/mucis/register.html文件~)

需要注意的是:别看我这注册和登录的页面一模一样,你就以为这俩直接共用一个模板就行了!真正使用的时候注册需要的信息是比登录要多,所以这俩不可能使用同一个模板。本处为了方便讲解,所以只建了个含有用户名和密码的模型。所以会造成注册和登录可以用同一个模板的假象! 不信你看我在下面注册模板中又随便加了个输入框,但是其实它没用,我只是为了强调这个问题!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
    <form action="" method="post">
        {% csrf_token %}
        <h2>注册</h2>
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>

        手机号:<input type="text" name="phone"><br>
        <button type="submit">注册</button>
    </form>
</body>
</html>

🔆In The End!

请添加图片描述

从现在做起,坚持下去,一天进步一小点,不久的将来,你会感谢曾经努力的你!

本博主会持续更新爬虫基础分栏及爬虫实战分栏,认真仔细看完本文的小伙伴们,可以点赞收藏并评论出你们的读后感。并可关注本博主,在今后的日子里阅读更多爬虫文!

如有错误或者言语不恰当的地方可在评论区指出,谢谢!
如转载此文请联系我征得本人同意,并标注出处及本博主名,谢谢 !