Django6 表單 註冊

2021-10-04 00:23:56 字數 3971 閱讀 4169

:# 用提交的資料生成表單

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模型的欄位名不一致

"註冊成功"

)else

:print

(form.__dict__)

# 驗證不成功,把錯誤資訊渲染到前端頁面

return render(request,

"register.html",)

return render(request,

"register.html"

)

from django import forms

from django.core.exceptions import validationerror

class

registerform

(forms.form)

: username = forms.charfield(min_length=

3,required=

true

,error_messages=

) password = forms.charfield(min_length=

3,required=

true

,error_messages=

) confirm = forms.charfield(min_length=

3,required=

true

,error_messages=

) regtime = forms.datetimefield(required=

false

,error_messages=

) *** = forms.booleanfield(required=

false

)# 單個字段驗證: clean_***x

defclean_password

(self)

: password = self.cleaned_data.get(

'password'

)if password and password.isdigit():

raise validationerror(

"密碼不能是純數字"

)return password

# 全域性驗證

defclean

(self)

: password = self.cleaned_data.get(

'password'

,none

) confirm = self.cleaned_data.get(

'confirm',''

)print

(password,confirm)

if password != confirm:

raise validationerror(

)return self.cleaned_data

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(

) *** = models.integerfield(blank=

true

, null=

true

)class

meta

: db_table =

'user'

lang

="en"

>

>

charset

="utf-8"

>

>

註冊title

>

head

>

>

action

= method

="post"

>

使用者名稱:type

="text"

name

="username"

>

>

}span

>

>

密碼:type

="password"

name

="password"

>

}>

確認密碼:type

="password"

name

="confirm"

>

}>

type

="text"

name

="regtime"

>

}>

性別:type

="radio"

name

="***"

value

="0"

>

女 type

="radio"

name

="***"

value

="1"

>

男 }

>

type

="submit"

value

="註冊"

>

form

>

body

>

html

>

Django 6 模型與資料庫 1

django 對各種資料庫提供了很好的支援,包括 postgresql mysql sqlite 和 oracle,而且為這些資料庫提供了統一的呼叫 api,這些 api 統稱為 orm 框架。通過使用 django 內建的 orm 框架可以實現資料庫連線和讀寫操作。orm 框架是一種程式技術,用於...

django學習筆記6 表單

django表單 mytest test1 forms.py from django import forms class addform forms.form a forms.integerfield b forms.integerfield 匯入相應的庫,定義表單輸入的型別 修改mytest t...

django 註冊介面

模型model 定義使用者類,用來註冊時使用 from django.db import models create your models here.class person models.model gender male 男 female 女 username models.charfield...