Django


1430 浏览 5 years, 9 months

6.1 表单字段设置

版权声明: 转载请注明出处 http://www.codingsoho.com/

field setting

Meta
model
fields / exclude
choice
class SafetyCheckFormMixin(object):
    try:
        CHOICE_LIST = []
        for ins in get_user_model().objects.all():
            if not (ins, ins) in CHOICE_LIST:
                CHOICE_LIST.append((ins, ins))
        CHOICE_LIST.sort()
        CHOICE_LIST.insert(0, ('', '----'))

    <span class="n">inspector</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">ChoiceField</span><span class="p">(</span>
            <span class="n">label</span><span class="o">=</span><span class="n">_</span><span class="p">(</span><span class="s1">&#39;Check Person&#39;</span><span class="p">),</span>
            <span class="n">choices</span> <span class="o">=</span> <span class="n">CHOICE_LIST</span><span class="p">,</span>
            <span class="n">required</span><span class="o">=</span><span class="bp">False</span>
            <span class="p">)</span>
except: pass
error message

方法1:required

class UserUpdateForm(forms.ModelForm):
    birthday = forms.DateField(label='birthday', 
        error_messages={'required':'birthday required'})

方法2:自定义通过raise报错ValidationError

class RegistrationForm(forms.Form):
    phone = forms.CharField(label='Phone', max_length=18)
    def clean_phone(self):
        phone = self.cleaned_data['phone']
        users = UserModel().objects.filter(phone=phone)
        if users :
            raise forms.ValidationError('User Exist!')
            return phone
        import re 
        pattern = re.compile(r'^(130|131|132|133|134|135|136|137|138|139)\d{8}$') 
        match = pattern.search(phone) 
        if not match:
            raise forms.ValidationError('Please input valid phone number !')
        return phone

方法3:在model中定义,根据内嵌的unique等定义error message或者自定义validation

class MyUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(_('username'), max_length=30, unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and '
                    '@/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(r'^[\w.@+-]+$',
                                      _('Enter a valid username. '
                                        'This value may contain only letters, numbers '
                                        'and @/./+/-/_ characters.'), 'invalid'),
        ],
        error_messages={
            'unique': _("A user with that username already exists."),
        })
readonly fields
    def __init__(self, *args, **kwargs):
        super(UserUpdateForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            self.fields['phone'].widget.attrs['readonly'] = True

    def clean_phone():
        instance = getattr(self, 'instance', None)
        if instance and instance.id:
            return instance.phone
        else:
            return self.cleaned_data['phone']       

或者

birthday = forms.DateField(label='birthday', 
        widget=forms.DateInput(attrs={'cols': 10, 'rows': 50, 'readonly':'readonly','disable':True}),  #WORK
        error_messages={'required':'birthday required'})

https://stackoverflow.com/questions/324477/in-a-django-form-how-do-i-make-a-field-readonly-or-disabled-so-that-it-cannot

base field

form里explict定义的field是base_field