1. 程式人生 > >Django(Form,ModelForm)

Django(Form,ModelForm)

utils -c 用法 note err object attrs date message

FORM表單:

Django表單系統中,所有的表單類都作為django.forms.Form的子類創建,包括ModelForm

關於django的表單系統,主要分兩種

基於django.forms.Form:所有表單類的父類

基於django.forms.ModelForm:可以和模型類綁定的Form

需求:向數據庫的Info表中添加一些新的個人信息

FORM的用法

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

class Info_form(forms.Form):

    def validate_name(value):
        try:
            models.Info.objects.get(name=value)
            raise ValidationError(‘%s 的信息已經存在!‘%value)
        except models.Info.DoesNotExist:
            pass

    sex_choice=((0,‘男‘),
                (1,‘女‘))#select的數據可以像這樣寫,也可以在另外一張表中動態去拿


    name = forms.CharField(validators=[validate_name],label=‘姓名‘,error_messages={‘required‘:‘必填‘})

    age = forms.CharField(label=‘年齡‘,error_messages={‘required‘:‘必填‘})

    # sex = forms.CharField(label=‘性別‘,error_messages={‘required‘:‘必填‘,},)
    sex=forms.IntegerField(widget=forms.widgets.Select(choices=sex_choice,

                                                       attrs={‘class‘:‘setform2‘}
                                                       ))

    birthday = forms.CharField(label=‘生日‘,error_messages={‘required‘:‘必填‘})

    qualification = forms.CharField(label=‘學歷‘,error_messages={‘required‘:‘必填‘},
                                    widget=forms.TextInput(attrs={‘class‘:‘formset‘,
                                                        ‘placeholder‘:‘本科‘
                                                        }
                                    ))
    email=forms.EmailField(max_length=100,min_length=10)

    job = forms.CharField(label=‘工作‘,error_messages={‘required‘:‘必填‘})



    def  __init__(self,*args,**kwargs):

        super(Info_form,self).__init__(*args,**kwargs)

        self.fields[‘hobby‘]=forms.CharField(widget=forms.widgets.Select(choices=models.Hobby.objects.values_list(‘id‘,‘item‘)))



#-------------------------------------------------------views.py
#-------------------------------------------------------


from django.shortcuts import render,HttpResponse

# Create your views here.

from app01.models import *

from app01.forms import *

def add_info(req):
    if req.method==‘POST‘:

        Info_form_obj=Info_form(req.POST)
        if Info_form_obj.is_valid():

            Info.objects.create(name=Info_form_obj.cleaned_data[‘name‘],
                                age=Info_form_obj.cleaned_data[‘age‘],
                                sex=Info_form_obj.cleaned_data[‘sex‘],
                                birthday=Info_form_obj.cleaned_data[‘birthday‘],
                                qualification=Info_form_obj.cleaned_data[‘qualification‘],
                                job=Info_form_obj.cleaned_data[‘job‘]
                             )
            return HttpResponse(‘添加成功!‘)
        else:

            error_obj=Info_form_obj.errors
            print(‘***************‘)
            print(type(error_obj))#<class ‘django.forms.utils.ErrorDict‘>

            print(error_obj[‘name‘][0])#必填

            print(error_obj.get(‘age‘))#<ul class="errorlist"><li>必填</li></ul>
            return render(req,‘add_info.html‘,{‘form_obj‘:Info_form_obj,‘error_obj‘:error_obj})


    Info_form_obj=Info_form()
    return render(req,‘add_info.html‘,{‘form_obj‘:Info_form_obj})


#------------------------------------------------------add_info.html
#-------------------------------------------------------

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加個人信息</title>
    <style>
        .formset{
            color: rebeccapurple;
            border: dashed cadetblue;
        }
    </style>
</head>
<body>
     <form action="{% url ‘add_info‘ %}" method="post">


         <p>姓名{{ form_obj.name }}{{ error_obj.name.0 }}</p>
         <p>年齡{{ form_obj.age }}{{ error_obj.age.0 }}</p>
         <p>生日{{ form_obj.birthday }}{{ error_obj.birthday.0 }}</p>
         <p>工作{{ form_obj.job }}<span>{{ error_obj.job }}</span></p>
         <p>學歷{{ form_obj.qualification }}<span>{{ error_obj.qualification }}</span></p>
         <p>性別{{ form_obj.sex }}<span>{{ error_obj.sex }}</span></p>
         <p>郵箱{{ form_obj.email }}<span>{{ error_obj.email }}</span></p>
         <p>愛好{{ form_obj.hobby }}<span>{{ error_obj.hobby }}</span></p>


         {#          {{ form_obj.as_p }}#}

           <input type="submit" value="提交"><br>
          {% csrf_token %}
     </form>
</body>
</html>


MODELFORM基本操作:

ModelForm
a. class Meta:

            model,                           # 對應Model的

            fields=None,                     # 字段

            exclude=None,                    # 排除字段

            labels=None,                     # 提示信息

            help_texts=None,                 # 幫助提示信息
widgets=None, # 自定義插件

            error_messages=None,             # 自定義錯誤信息(整體錯誤信息from django.core.exceptions import NON_FIELD_ERRORS)

            field_classes=None               # 自定義字段類 (也可以自定義字段)

            localized_fields=(‘birth_date‘,) # 本地化,如:根據不同時區顯示數據
如:

                數據庫中

                    2016-12-27 04:10:57

                setting中的配置

                    TIME_ZONE = ‘Asia/Shanghai‘

                    USE_TZ = True

                則顯示:

                    2016-12-27 12:10:57

    b. 驗證執行過程

        is_valid -> full_clean -> 鉤子 -> 整體錯誤

 

    c. 字典字段驗證

        def clean_字段名(self):

            # 可以拋出異常

            # from django.core.exceptions import ValidationError

            return "新值"

    d. 用於驗證

        model_form_obj = XXOOModelForm()

        model_form_obj.is_valid()

        model_form_obj.errors.as_json()

        model_form_obj.clean()

        model_form_obj.cleaned_data

    e. 用於創建

        model_form_obj = XXOOModelForm(request.POST)

        #### 頁面顯示,並提交 #####

        # 默認保存多對多

            obj = form.save(commit=True)

        # 不做任何操作,內部定義 save_m2m(用於保存多對多)

            obj = form.save(commit=False)

            obj.save()      # 保存單表信息

            obj.save_m2m()  # 保存關聯多對多信息

 

    f. 用於更新和初始化

        obj = model.tb.objects.get(id=1)

        model_form_obj = XXOOModelForm(request.POST,instance=obj)

        ...

 

        PS: 單純初始化

            model_form_obj = XXOOModelForm(initial={...})
 

Django(Form,ModelForm)