Bootstrap

Django中 modelform 详细使用方法

Django modelform 在使用方面优于model to model 的模式,无需在view视图中再次保存一遍,对应的语法与结构也更加的简单明了!
在model中定义我们需要的字段类型

class CustomerInfo(models.Model):
    '''客户信息表'''
    customer_id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=32,blank=True,null=True)
    qq = models.CharField(max_length=64,unique=True)
    phone_number = models.BigIntegerField(max_length=32,unique=True)
    contact_type_choices = ((0,"QQ"),(1,"微信"),(2,"手机"))
    contact_type = models.SmallIntegerField(choices=contact_type_choices,default=0,verbose_name='联系方式')
    sigin_date = models.DateField(auto_now_add=True)
    Email = models.CharField(max_length=64,unique=True)
    source_choices = ((0,'转介绍'),(1,'广告'),(2,'百度推广'),(3,'QQ群'),(4,'知乎'),(5,'朋友'),(6,'微信'),(7,'市场推广'))
    source = models.SmallIntegerField(choices=source_choices)
    tags = models.ManyToManyField("Tag",blank=True,null=True)
    status_choices = ((0,'已报名'),(1,'未报名'))
    status = models.SmallIntegerField(choices=status_choices,default=1)
    profession = models.CharField(max_length=64)      #职业
    age = models.IntegerField(max_length=12)
    roles = models.ManyToManyField(to="Roles")                       #客户对应的角色 ,多对多
    def __str__(self):
        return self.name

在view 中定义一个类,并指定我们需要转换为modelform 的表

from django.shortcuts import render,HttpResponse,redirect
from django import forms
from django.forms import ModelForm
from permission_manager import models
from django.forms import widgets as wid

# Create your views here.


class CustomerInfoForm(ModelForm):
    class Meta:
        model = models.CustomerInfo
        fields = "__all__"  # 或('name','email','user_type')    #验证哪些字段,"__all__"表示所有字段
        exclude = None  # 排除的字段
        labels ={                                   #将英文字段转换为中文字段
            "title":"书籍名称",
            "price":"价格"
        }
        help_texts = None  # 帮助提示信息
        error_messages = None  # 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS)
        field_classes = None  # 自定义字段类(也阔以自定义字段)
        localized_fields = ()  # 本地化,根据settings中TIME_ZONE设置的不同时区显示时间
        widgets = {
            "title":wid.TextInput(attrs={"class":"form-control"}),
            "date": wid.DateTimeInput(attrs={"class": "form-control"}),         #设置前端显示为日期显示格式
            "publish": wid.SelectMultiple(attrs={"class": "form-control"}),     #设置前端显示为选择框格式
        }

view中的字段的增删改查的代码也变换为:

def addcustomer(request):
    if request.method=="POST":
        form = CustomerInfoForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/customer/")
    form=CustomerInfoForm()
    return  render(request,"customer.html",locals())

直接对form进行保存,无需对字段进行creat,update,

;