Django之form表單那點事

來源:互聯網
上載者:User

標籤:預設值   objects   ***   添加   分享圖片   功能   length   顯示   _for   

Form介紹 

我們之前在HTML頁面中利用form表單向後端提交資料時,都會寫一些擷取使用者輸入的標籤並且用form標籤把它們包起來。

與此同時我們在好多情境下都需要對使用者的輸入做校正,比如校正使用者是否輸入,輸入的長度和格式等正不正確。如果使用者輸入的內容有錯誤就需要在頁面上相應的位置顯示對應的錯誤資訊.。

Django form組件就實現了上面所述的功能。

總結一下,其實form組件的主要功能如下:

  • 產生頁面可用的HTML標籤
  • 對使用者提交的資料進行校正
  • 保留上次輸入內容
普通方式手寫註冊功能views.py
# 註冊def register(request):    error_msg = ""    if request.method == "POST":        username = request.POST.get("name")        pwd = request.POST.get("pwd")        # 對註冊資訊做校正        if len(username) < 6:            # 使用者長度小於6位            error_msg = "使用者名稱長度不能小於6位"        else:            # 將使用者名稱和密碼存到資料庫            return HttpResponse("註冊成功")    return render(request, "register.html", {"error_msg": error_msg})
login.html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>註冊頁面</title></head><body><form action="/reg/" method="post">    {% csrf_token %}    <p>        使用者名稱:        <input type="text" name="name">    </p>    <p>        密碼:        <input type="password" name="pwd">    </p>    <p>        <input type="submit" value="註冊">        <p style="color: red">{{ error_msg }}</p>    </p></form></body></html>
使用form組件實現註冊功能views.py

先定義好一個RegForm類:

from django import forms# 按照Django form組件的要求自己寫一個類class RegForm(forms.Form):    name = forms.CharField(label="使用者名稱")    pwd = forms.CharField(label="密碼")

再寫一個視圖函數:

# 使用form組件實現註冊方式def register2(request):    form_obj = RegForm()    if request.method == "POST":        # 執行個體化form對象的時候,把post提交過來的資料直接傳進去        form_obj = RegForm(request.POST)        # 調用form_obj校正資料的方法        if form_obj.is_valid():            return HttpResponse("註冊成功")    return render(request, "register2.html", {"form_obj": form_obj})
login2.html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>註冊2</title></head><body>    <form action="/reg2/" method="post" novalidate autocomplete="off">        {% csrf_token %}        <div>            <label for="{{ form_obj.name.id_for_label }}">{{ form_obj.name.label }}</label>            {{ form_obj.name }} {{ form_obj.name.errors.0 }}        </div>        <div>            <label for="{{ form_obj.pwd.id_for_label }}">{{ form_obj.pwd.label }}</label>            {{ form_obj.pwd }} {{ form_obj.pwd.errors.0 }}        </div>        <div>            <input type="submit" class="btn btn-success" value="註冊">        </div>    </form></body></html>

看網頁效果發現 也驗證了form的功能:
•前端頁面是form類的對象產生的                                      -->產生HTML標籤功能
•當使用者名稱和密碼輸入為空白或輸錯之後 頁面都會提示        -->使用者提交校正功能
•當使用者輸錯之後 再次輸入 上次的內容還保留在input框   -->保留上次輸入內容

Form那些事兒常用欄位與外掛程式

建立Form類時,主要涉及到 【欄位】 和 【外掛程式】,欄位用於對使用者請求資料的驗證,外掛程式用於自動產生HTML;

initial

初始值,input框裡面的初始值。

class LoginForm(forms.Form):    username = forms.CharField(        min_length=8,        label="使用者名稱",        initial="張三"  # 設定預設值    )    pwd = forms.CharField(min_length=6, label="密碼")
error_messages

重寫錯誤資訊。

class LoginForm(forms.Form):    username = forms.CharField(        min_length=8,        label="使用者名稱",        initial="張三",        error_messages={            "required": "不可為空",            "invalid": "格式錯誤",            "min_length": "使用者名稱最短8位"        }    )    pwd = forms.CharField(min_length=6, label="密碼")
password
class LoginForm(forms.Form):    ...    pwd = forms.CharField(        min_length=6,        label="密碼",        widget=forms.widgets.PasswordInput(attrs={‘class‘: ‘c1‘}, render_value=True)    )
radioSelect

單radio值為字串

class LoginForm(forms.Form):    username = forms.CharField(        min_length=8,        label="使用者名稱",        initial="張三",        error_messages={            "required": "不可為空",            "invalid": "格式錯誤",            "min_length": "使用者名稱最短8位"        }    )    pwd = forms.CharField(min_length=6, label="密碼")    gender = forms.fields.ChoiceField(        choices=((1, "男"), (2, "女"), (3, "保密")),        label="性別",        initial=3,        widget=forms.widgets.RadioSelect()    )
單選Select
class LoginForm(forms.Form):    ...    hobby = forms.fields.ChoiceField(        choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ),        label="愛好",        initial=3,        widget=forms.widgets.Select()    )
多選Select
class LoginForm(forms.Form):    ...    hobby = forms.fields.MultipleChoiceField(        choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ),        label="愛好",        initial=[1, 3],        widget=forms.widgets.SelectMultiple()    )
單選checkbox
class LoginForm(forms.Form):    ...    keep = forms.fields.ChoiceField(        label="是否記住密碼",        initial="checked",        widget=forms.widgets.CheckboxInput()    )
多選checkbox
class LoginForm(forms.Form):    ...    hobby = forms.fields.MultipleChoiceField(        choices=((1, "籃球"), (2, "足球"), (3, "雙色球"),),        label="愛好",        initial=[1, 3],        widget=forms.widgets.CheckboxSelectMultiple()    )

關於choice的注意事項:

在使用選擇標籤時,需要注意choices的選項可以從資料庫中擷取,但是由於是靜態欄位 ***擷取的值無法即時更新***,那麼需要自訂構造方法從而達到此目的。

方式一:

from django.forms import Formfrom django.forms import widgetsfrom django.forms import fields class MyForm(Form):     user = fields.ChoiceField(        # choices=((1, ‘上海‘), (2, ‘北京‘),),        initial=2,        widget=widgets.Select    )     def __init__(self, *args, **kwargs):        super(MyForm,self).__init__(*args, **kwargs)        # self.fields[‘user‘].choices = ((1, ‘上海‘), (2, ‘北京‘),)        # 或        self.fields[‘user‘].choices = models.Classes.objects.all().values_list(‘id‘,‘caption‘)

方式二:

from django import formsfrom django.forms import fieldsfrom django.forms import models as form_model class FInfo(forms.Form):    authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all())  # 多選    # authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all())  # 單選
Django Form所有內建欄位校正

方式一:

from django.forms import Formfrom django.forms import widgetsfrom django.forms import fieldsfrom django.core.validators import RegexValidator class MyForm(Form):    user = fields.CharField(        validators=[RegexValidator(r‘^[0-9]+$‘, ‘請輸入數字‘), RegexValidator(r‘^159[0-9]+$‘, ‘數字必須以159開頭‘)],    )

方式二:

import refrom django.forms import Formfrom django.forms import widgetsfrom django.forms import fieldsfrom django.core.exceptions import ValidationError  # 自訂驗證規則def mobile_validate(value):    mobile_re = re.compile(r‘^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$‘)    if not mobile_re.match(value):        raise ValidationError(‘手機號碼格式錯誤‘)  class PublishForm(Form):      title = fields.CharField(max_length=20,                            min_length=5,                            error_messages={‘required‘: ‘標題不可為空‘,                                            ‘min_length‘: ‘標題最少為5個字元‘,                                            ‘max_length‘: ‘標題最多為20個字元‘},                            widget=widgets.TextInput(attrs={‘class‘: "form-control",                                                          ‘placeholder‘: ‘標題5-20個字元‘}))      # 使用自訂驗證規則    phone = fields.CharField(validators=[mobile_validate, ],                            error_messages={‘required‘: ‘手機不可為空‘},                            widget=widgets.TextInput(attrs={‘class‘: "form-control",                                                          ‘placeholder‘: u‘手機號碼‘}))     email = fields.EmailField(required=False,                            error_messages={‘required‘: u‘郵箱不可為空‘,‘invalid‘: u‘郵箱格式錯誤‘},                            widget=widgets.TextInput(attrs={‘class‘: "form-control", ‘placeholder‘: u‘郵箱‘}))
補充進階應用Bootstrap樣式 Django form應用Bootstrap樣式簡單樣本大量新增樣式

可通過重寫form類的init方法來實現。

 大量新增樣式ModelForm

form與model的終極結合。

class BookForm(forms.ModelForm):    class Meta:        model = models.Book        fields = "__all__"        labels = {            "title": "書名",            "price": "價格"        }        widgets = {            "password": forms.widgets.PasswordInput(attrs={"class": "c1"}),        }

 class Meta:下常用參數:

model = models.Student  # 對應的Model中的類fields = "__all__"  # 欄位,如果是__all__,就是表示列出所有的欄位exclude = None  # 排除的欄位labels = None  # 提示資訊help_texts = None  # 協助提示資訊widgets = None  # 自訂外掛程式error_messages = None  # 自訂錯誤資訊

Django之form表單那點事

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.