Python菜鸟之路:Django ModelForm的使用
一、简单使用案例
python;gutter:true;">#views.py#views.py
from django.shortcuts import render,HttpResponse
from app01 import models
from django import forms
from django.forms import fields as Ffields
from django.forms import widgets as Fwidgets
class UserInfoModelForm(forms.ModelForm):
is_rmb = Ffields.CharField(widget=Fwidgets.CheckboxInput())
class Meta:
model = models.UserInfo
fields = '__all__'
# fields = ['username','email']
# exclude = ['username']
labels = {
'username': '用户名',
'email': '邮箱',
}
help_texts = {
'username': '...'
}
widgets = {
'username': Fwidgets.Textarea(attrs={'class': 'c1'})
}
error_messages = {
'__all__':{
},
'email': {
'required': '邮箱不能为空',
'invalid': '邮箱格式错误..',
}
}
field_classes = {
# 'email': Ffields.URLField
}
# localized_fields=('ctime',)
def clean_username(self):
old = self.cleaned_data['username']
return old
def index(request):
if request.method == "GET":
obj = UserInfoModelForm()
return render(request,'index.html',{'obj': obj})
elif request.method == "POST":
obj = UserInfoModelForm(request.POST)
if obj.is_valid():
# obj.save() 等效于下面的3条
instance = obj.save(False)
instance.save() # 这样的话只会保存当前的类到数据库,并不会保存关联的多对多关系到U2G表中
obj.save_m2m() # 保存many to many的关系到数据库
# print(obj.is_valid())
# print(obj.cleaned_data)
# print(obj.errors.as_json())
return render(request,'index.html',{'obj': obj})
#models.pyfrom django.db import models
# Create your models here.
class UserType(models.Model):
caption = models.CharField(max_length=32)
class UserGroup(models.Model):
name = models.CharField(max_length=32)
class UserInfo(models.Model):
username = models.CharField(max_length=32)
email = models.EmailField()
user_type = models.ForeignKey(to='UserType',to_field='id')
u2g = models.ManyToManyField(UserGroup)
总结: 从上边可以看到ModelForm用起来也是非常方便的,比如增加修改之类的操作。但是也带来额外不好的地方,model和model之间耦合了。如果不耦合的话,mf.save()方法也无法直接提交保存。 但是耦合的话使用场景通常局限用于小程序,写大程序就最好不用了
以上是 Python菜鸟之路:Django ModelForm的使用 的全部内容, 来源链接: utcz.com/z/389311.html