Django6 表單 註冊

urls

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("App.urls")),
]

App.urls

from django.urls import path
from App import views

app_name = "App"
urlpatterns = [
    path('register/', views.register, name='register'),
]

App.views

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from App.forms import RegisterForm
from App.models import User


def register(request):
    if request.method == "POST":
        # 用提交的數據生成表單
        form =RegisterForm(request.POST)
        # 能通過驗證,返回True,否則返回False
        if form.is_valid():
            # 進行業務處理
            data = form.cleaned_data
            data.pop("confirm")
            # 如果forms中表單的字段名和models模型的字段名一致
            res = User.objects.create(**data)
            # 如果forms中表單的字段名和models模型的字段名不一致
            res = User.objects.create(username=form.cleaned_data.get('username',),password=form.cleaned_data.get('password'))
            if res:
                return HttpResponse("註冊成功")
        else:
            print(form.__dict__)
            # 驗證不成功,把錯誤信息渲染到前端頁面
            return render(request, "register.html",{'form':form})
    return render(request,"register.html")

App.forms

from django import forms
from django.core.exceptions import ValidationError

class RegisterForm(forms.Form):
    username = forms.CharField(min_length=3,required=True,error_messages={
        'required':'用戶名必須輸入',
        'min_length':'用戶名至少3個字符'
    })
    password = forms.CharField(min_length=3,required=True,error_messages={
        'required': '密碼名必須輸入',
        'min_length': '密碼至少3個字符'
    })
    confirm = forms.CharField(min_length=3,required=True,error_messages={
        'required': '密碼名必須輸入',
        'min_length': '密碼至少3個字符'
    })
    regtime = forms.DateTimeField(required=False,error_messages={
        'invalid':'日期格式錯誤',
    })
    sex = forms.BooleanField(required=False)

    # 單個字段驗證: clean_xxxx
    def clean_password(self):
        password = self.cleaned_data.get('password')
        if password and password.isdigit():
            raise ValidationError("密碼不能是純數字")
        return password


    # 全局驗證
    def clean(self):
        password = self.cleaned_data.get('password',None)
        confirm = self.cleaned_data.get('confirm','')
        print(password,confirm)
        if password != confirm:
            raise ValidationError({'confirm':"兩次密碼輸入不一致"})
        return self.cleaned_data


App.models

from django.db import models

class User(models.Model):
    uid = models.AutoField(primary_key=True)
    username = models.CharField(unique=True, max_length=30)
    password = models.CharField(max_length=128)
    regtime = models.DateTimeField()
    sex = models.IntegerField(blank=True, null=True)

    class Meta:
        db_table = 'user'

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>註冊</title>
</head>
<body>
<form action="{% url 'App:register' %}" method="post">
    {% csrf_token %}
    用戶名:<input type="text" name="username">
    {% for error in form.username.errors %}
        <span>{{ error }}</span>
    {% endfor %}
    <br>
    密碼:<input type="password" name="password">
    {{ form.password.errors }}
    <br>
    確認密碼:<input type="password" name="confirm">
     {{ form.confirm.errors }}
    <br>
    註冊時間:<input type="text" name="regtime">
     {{ form.regtime.errors }}
    <br>
    性別:<input type="radio" name="sex" value="0"><input type="radio" name="sex" value="1"> 男
     {{ form.sex.errors }}
    <br>
    <input type="submit" value="註冊">
</form>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章