Django-Modelform中設置新增字段() class Meta


from django import forms
from app01.models import UserInfo
from django.forms import fields as Ffields
from django.forms import widgets as Fwidgets
import time, datetime


class UserInfoModelForm(forms.ModelForm):
    age = Ffields.IntegerField(
        label='年齡',
        widget=Fwidgets.TextInput(attrs={'class': 'form-control'}),
        initial=22
    )
    gender = Ffields.CharField(
        label='性別',
        widget=Fwidgets.TextInput(attrs={'class': 'form-control'}),
        initial=''
    )
    birth = Ffields.DateField(
        label='生日',
        widget=Fwidgets.DateTimeInput()
    )

    class Meta:
        # 與models建立了依賴關系.........................................
        model = UserInfo

        # 字段.........................................................
        fields = ['username', 'email', 'user_type', 'age']

        # 排除字段......................................................
        exclude = None,

        # 幫助提示信息...................................................
        help_texts = {
                         'username': '請輸入賬號',
                         'email': '請輸入郵箱地址',
                         'user_type': '請選擇客戶類型'
                     },

        # 自定義插件.....................................................
        widgets = {
                      'username': Fwidgets.TextInput(attrs={'class': 'form-control'})
                  },

        # 自定義字段類(也可以自定義字段)...................................
        field_classes = {
            # 設置此處,前端輸入時,就必須是url,否則提示錯誤
            # 'email': Ffields.URLField,
        }

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

        # 如果此處不寫,會顯示數據庫模型設置的verbose_name....................
        labels = {
            'username': '賬號',
            'email': '郵箱',
            'user_type': '類型'
        }

        # 自定義錯誤信息..................................................
        # 整體錯誤信息from django.core.exceptions import NON_FIELD_ERRORS
        error_messages = {
            '__all__': {
                'required': '此處不能為空'
            },
            'age': {
                'invalid': '請輸入一個有效的年齡'
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM