zoukankan      html  css  js  c++  java
  • Django的ModelForm

    1. form

      from django import forms
      from django.core.exceptions import  ValidationError
      
      class RegForm(forms.Form):
          name = forms.CharField(
              required = True,
              min_length =6,
              label = '姓名',
              error_messages = {
                  'required':'不能为空',
                  'invalid':'格式不正确'
              }
          	)
          password = forms.CharField(widget=forms.PassworInput())
          gender = forms.ChoicesField(choices=((1,'男'),(2,'女')))
          
          
          #局部钩子
      	def clean_name(self):
          	# 通过校验  返回正确的值
              # 不通过校验  抛出异常  raise ValidationError('错误信息')
          # 全局钩子
          def clean(self):
              # 通过校验  返回self.cleaned_data
              # 不通过校验 
              # 自己将错误信息添加到指定字段 self.add_error(’‘,'错误信息' )
      	    # 抛出异常  raise ValidationError('错误信息')
          
      # 视图中使用:
      form_obj = RegForm()
      
      form_obj = RegForm(request.POST)
      form_obj.is_valid()
      form_obj.fields  #  有序字典  name:字段的对象
      # 模板中使用:
      {{ form_obj.as_p }}
      {{ form_obj.errors }}
      {{ form_obj.name }}
      {{ form_obj.name.label }}
      {{ form_obj.name.id_for_label }}  
      {{ form_obj.name.errors }}  {{ form_obj.name.errors.0 }}  
      
      
    2. modelform

    from django import forms
    from app01 import models
    
    class RegForm(forms.ModelForm):
        re_password = forms.CharField(widget=forms.PassworInput())
        
        class Meta:
            model = models.User
            fields = '__all__'   #   ['name','password']
            exclude = ['name']
            labels = {
                'name':'姓名'    # 直接给model中的字段加verbose_name 
            }
            error_messages={
                'name' = {
                         }
            }
            widgets = {
                'password':widget=forms.PassworInput(attrs={'class':'form-control'})           
            }
       	def __init__(self,*args,**kwargs):
            super().__init__(*args,**kwargs)
            for field in self.fields.values():
                field.widget.attrs.update({'class':'form-control'})
            
            
    # 视图中使用:
    form_obj = RegForm(request.POST)
    form_obj.is_valid():
        form_obj.save()
        
    
  • 相关阅读:
    shell 学习笔记4-shell内置变量命令
    shell 学习笔记3-shell变量扩展
    vmware vSphere Data Protection 6.1 --------3-使用备份、恢复、报告
    shell 学习笔记2-shell-test
    vmware vSphere Data Protection 6.1--------2-初始化
    Centos7+puppet+foreman,模板介绍
    vmware vSphere Data Protection 6.1 --------1-部署
    vmware vcsa-故障1
    Grafana重置admin登录密码
    MongoDB远程连接报错
  • 原文地址:https://www.cnblogs.com/russellyoung/p/10134762.html
Copyright © 2011-2022 走看看