Django學習系列之Form基礎

Form對與一個網站來講就是一個靈魂,今天咱們就來講說Django的Form概述.html

本文內容來自官網,互聯網及本身實驗所得.django


表單(forms.py)的定義:ide

#coding:utf-8
from django import forms
from django.forms.extras.widgets import SelectDateWidget

SEX_CHOICES=(
('male','男'),
('female','女')
)

BIRTH_YEAR_CHOICES = ('1980', '1981', '1982','1983','1984')

#註冊表單
class Register(forms.Form):
    nickname = forms.CharField(max_length=20,label="暱稱",help_text="請輸入您的別名!",widget=forms.TextInput(attrs={'class':'special','id':'nick'}),error_messages={'required':u'別名不能爲空'})
    username = forms.CharField(label="用戶名",error_messages={'required':u'用戶名不能爲空'})
    password = forms.CharField(label="密碼",widget=forms.PasswordInput)
    sex = forms.ChoiceField(widget=forms.RadioSelect,choices=SEX_CHOICES,label="性別")
    email = forms.EmailField(label="郵箱",error_messages={'required':u'郵箱不能爲空','invalid':u'請輸入正確的郵箱'})
    phone = forms.CharField(required=False,label="手機號")
    birthday = forms.DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))網站

以上是表單常用的屬性,供其參考.ui

如,咱們須要更改某個表單默認的元素就須要使用widget,而且改變其元素屬性就須要使用attrs。spa


視圖(應用)邏輯
code

views.pyorm

#coding:utf-8
from django.shortcuts import render
from django.http import HttpResponse
from forms import Register
from django.forms.util import ErrorList
# Create your views here.

#從新定義檢驗錯誤輸出
class DivErrorList(ErrorList):
    def __unicode__(self):
        return self.as_divs()

    def as_divs(self):
        if not self: return u''
        return u'%s' %''.join([u'<div class="error">%s</div>' % e for e in self])

def register(request):
    if request.method == 'POST':
         regform = Register(request.POST,auto_id="%s",error_class=DivErrorList)
         if regform.is_valid():
             nickname = regform.cleaned_data['nickname'] #別名
             #print nickname
             return HttpResponse(u"{0},歡迎您!".format(nickname))
    else:
         regform = Register(auto_id="%s",label_suffix=":") #auto_id有3種設置:True/False/str 如果False不須要html元素中的id標識與True相反,auto_id="%s",則是field的名字
    return render(request,"register.html",{'reg':regform})csrf


模板htm

base.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
{% block title %}
首頁
{% endblock%}
</title>
</head>
<body>
{% block content %}
這是內容
{% endblock %}
</body>
</html>


register.html

{% extends "base.html" %}
{% block title %}
用戶註冊
{% endblock %}

{% block content %}

<form method="POST">{% csrf_token %}
<label><h1>用戶註冊</h1></label></br>

{% comment%}
{% for err_label,err_value in reg.errors.items %}
    `err_label`:`err_value`
{% endfor %}
{% endcomment %}

<label>別名:</label>`reg`.`nickname` `reg`.`nickname`.`help_text` {{reg.nickname.errors|safe}}</br>
<label>用戶名:</label>`reg`.`username` {{reg.username.errors|safe}}</br>
<label>密碼:</label>`reg`.`password`</br>
<label>性別:</label>
{% for sex in reg.sex %}
   ` sex `
{% endfor %}
</br>
<label>郵箱:</label>`reg`.`email`{{reg.email.errors|safe}}</br>
<label>電話:</label>`reg`.`phone`</br>
<label>生日:</label>`reg`.`birthday`</br>
<input type="submit" value="註冊"/>
</form>

{% endblock %}


長啥子樣?

wKiom1VVLCeTYt82AAEQQmDdGpM940.jpg


表單基礎經過以上,基本也就這樣了,後面就要去研究下表單數據驗證這塊!


若是想了解更多,請關注咱們的公衆號
公衆號ID:opdevos
掃碼關注

gongzhouhao.jpg

相關文章
相關標籤/搜索