訂單交易平臺三(登入介面整個實現過程)階段一(只實現簡單的登入功能)

tmars發表於2024-10-05

1.在檢視函式account進行寫程式碼邏輯(需要了解django中form元件的知識、md5碼加密、指令碼的編寫)

1.1 登入介面後端的編寫

"""  在account.py檔案   """

from django.shortcuts import render, redirect
from web import models

from utils.encrypt import md5

# 1.定義類
from django import forms


class LoginForm(forms.Form):
    role = forms.ChoiceField(
        required=True,
        choices=(("2", "客戶"), ("1", "管理員")),
        widget=forms.Select(attrs={"class": "form-control"})
    )
    username = forms.CharField(
        required=True,
        widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "使用者名稱"})
    )
    password = forms.CharField(
        required=True,
        widget=forms.PasswordInput(attrs={"class": "form-control", "placeholder": "密碼"},render_value=True)
    )


def login(request):
    if request.method == "GET":
        form = LoginForm()
        return render(request, "login.html", {"form": form})

    # 1.接收並獲取資料(資料格式或是否為空驗證 - Form元件 & ModelForm元件)
    form = LoginForm(data=request.POST)
    if not form.is_valid():
        print("驗證失敗")
        return render(request, "login.html", {"form": form})

    # {'role': '1', 'username': 'asdfasdf', 'password': '123123'}
    # print(form.cleaned_data)  # {"username":'',"password":'xxx","role":xxx}
    role = form.cleaned_data.get("role")
    username = form.cleaned_data.get("username")
    password = form.cleaned_data.get("password")
    password = md5(password)

    # 2.去資料庫校驗  1管理員  2客戶
    mapping = {"1": "ADMIN", "2": "CUSTOMER"}
    if role not in mapping:
        return render(request, "login.html", {'form': form, 'error': "角色不存在"})

    if role == "1":
        user_object = models.Administrator.objects.filter(active=1, username=username, password=password).first()
    else:
        user_object = models.Customer.objects.filter(active=1, username=username, password=password).first()

    # 2.1 校驗失敗
    if not user_object:
        return render(request, "login.html", {'form': form, 'error': "使用者名稱或密碼錯誤"})

    # 2.2 校驗成功,使用者資訊寫入session+進入專案後臺
    request.session['user_info'] = {'role': mapping[role], 'name': user_object.username, 'id': user_object.id}

    return redirect("/level/list/")

1.2 使用兩個指令碼(在script檔案中進行建立、編寫)

"""  在init_admin.py檔案中   """

# 啟動django
import os
import sys
import django

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'day06.settings')
django.setup()  # 偽造讓django啟動

from web import models
from utils.encrypt import md5

models.Administrator.objects.create(username='root', password=md5("root"), mobile="1888888889")

"""  在init_customer.py檔案中   """

# 啟動django
import os
import sys
import django

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'day06.settings')
django.setup()  # 偽造讓django啟動

from web import models
from utils.encrypt import md5

# 建立級別
# level_object = models.Level.objects.create(title="VIP", percent=90)

models.Customer.objects.create(
    username='xinchen',
    password=md5("xinchen"),
    mobile='1999999998',
    level_id=1,
    creator_id=1
)

1.3 md5碼加密

"""  在encrypt.py檔案中   """


import hashlib
from django.conf import settings


def md5(data_string):
    obj = hashlib.md5(settings.SECRET_KEY.encode('utf-8'))
    obj.update(data_string.encode('utf-8'))
    return obj.hexdigest()

img

2.前端介面的編寫

2.1 登入介面的編寫

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap/css/bootstrap.css' %}">
    <style>
        .box {
            width: 450px;
            border: 1px solid #f0f0f0;
            margin-left: auto;
            margin-right: auto;
            margin-top: 100px;

            padding-left: 40px;
            padding-right: 40px;
            padding-bottom: 30px;

            box-shadow: 5px 10px 10px rgb(0 0 0 / 5%);
        }
    </style>
</head>
<body>

<div class="box">
    <h2 style="text-align: center;">使用者登入</h2>
    <form method="post" novalidate>
        {% csrf_token %}
        <div class="form-group">
            <label>角色</label>
            {{ form.role }}
        </div>
        <div class="form-group">
            <label>使用者名稱</label>
            {{ form.username }}
        </div>
        <div class="form-group">
            <label>密碼</label>
            {{ form.password }}
        </div>
        <button type="submit" class="btn btn-primary">登 錄</button>
        <span style="color: red;">{{ error }}</span>

        <a href='{% url 'sms_login' %}' style="float: right;">簡訊登入</a>
    </form>
</div>

</body>
</html>

2.2 簡訊登入介面的編寫

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap/css/bootstrap.css' %}">
    <style>
        .box {
            width: 450px;
            border: 1px solid #f0f0f0;
            margin-left: auto;
            margin-right: auto;
            margin-top: 100px;

            padding-left: 40px;
            padding-right: 40px;
            padding-bottom: 30px;

            box-shadow: 5px 10px 10px rgb(0 0 0 / 5%);
        }
    </style>
</head>
<body>
<div class="box">
    <form method="post">
        <h2 style="text-align: center;">簡訊登入</h2>
        {% csrf_token %}
        <div class="form-group">
            <label>手機號</label>
            <input type="text" class="form-control" placeholder="手機號">
        </div>
        <div class="form-group">
            <label>簡訊驗證碼</label>
            <div class="row">
                <div class="col-xs-7">
                    <input type="text" class="form-control" placeholder="簡訊驗證碼">
                </div>
                <div class="col-xs-5">
                    <input type="button" value="傳送簡訊" class="btn btn-default"/>
                </div>
            </div>

        </div>


        <button type="submit" class="btn btn-primary">登 錄</button>
        <a href="{% url 'login' %}" style="float: right;">使用者名稱登入</a>
    </form>
</div>
</body>
</html>

相關文章