ModelForm a. class Meta: model, # 对应Model的 fields=None, # 字段 exclude=None, # 排除字段 labels=None, # 提示信息 help_texts=None, # 帮助提示信息 widgets=None, # 自定义插件 error_messages=None, # 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS) field_classes=None # 自定义字段类 (也可以自定义字段) localized_fields=(‘birth_date‘,) # 本地化,如:根据不同时区显示数据 如: 数据库中 2016-12-27 04:10:57 setting中的配置 TIME_ZONE = ‘Asia/Shanghai‘ USE_TZ = True 则显示: 2016-12-27 12:10:57 b. 验证执行过程 is_valid -> full_clean -> 钩子 -> 整体错误 c. 字典字段验证 def clean_字段名(self): # 可以抛出异常 # from django.core.exceptions import ValidationError return "新值" d. 用于验证 model_form_obj = XXOOModelForm() model_form_obj.is_valid() model_form_obj.errors.as_json() model_form_obj.clean() model_form_obj.cleaned_data e. 用于创建 model_form_obj = XXOOModelForm(request.POST) #### 页面显示,并提交 ##### # 默认保存多对多 obj = form.save(commit=True) # 不做任何操作,内部定义 save_m2m(用于保存多对多) obj = form.save(commit=False) obj.save() # 保存单表信息 obj.save_m2m() # 保存关联多对多信息 f. 用于更新和初始化 obj = model.tb.objects.get(id=1) model_form_obj = XXOOModelForm(request.POST,instance=obj) ... PS: 单纯初始化 model_form_obj = XXOOModelForm(initial={...})
views.py
from django.shortcuts import render from django import forms from django.forms import fields as Ffields from django.forms import widgets as Fwidgets from app01 import models # Create your views here. 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": "邮箱格式错误" } }, # fields_classes = { # "email": Ffields.URLField # }, # localized_fields=() class UserInfoForm(forms.Form): username = Ffields.CharField() email = Ffields.EmailField() user_type = Ffields.ChoiceField( choices=models.UserType.objects.values_list("id", "caption") ) def __init__(self, *args, **kwargs): super(UserInfoForm, self).__init__(*args, **kwargs) self.fields["user_type"].choices = models.UserType.objects.values_list("id", "caption") 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() # models.UserInfo.objects.create(**obj.cleaned_data) # models.UserInfo.objects.filter(id=1).update(**obj.cleaned_data) return render(request, "index.html", {"obj": obj}) def user_list(request): li = models.UserInfo.objects.all().select_related("user_type") return render(request, "user_list.html", {"li": li}) def user_edit(request, nid): # 获取当前ID对象的用户信息 # 显示用户已经存在的数据 if request.method == "GET": user_obj = models.UserInfo.objects.filter(id=nid).first() mf = UserInfoModelForm(instance=user_obj) return render(request, "user_edit.html", {"mf": mf, "nid": nid}) elif request.method == "POST": user_obj = models.UserInfo.objects.filter(id=nid).first() mf = UserInfoModelForm(request.POST, instance=user_obj) if mf.is_valid(): mf.save() else: print(mf.errors.as_json()) return render(request, "user_edit.html", {"mf": mf, "nid": nid})
models.py
from 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)
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/index/" method="POST"> {% csrf_token %} {{ obj.as_p }} <input type="submit" value="提交"/> </form> </body> </html>
user_list.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for row in li %} <li>{{ row.username }} - {{ row.user_type.caption }} - <a href="/edit-{{ row.id }}/">编辑</a></li> {% endfor %} </ul> </body> </html>
user_edit.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/edit-{{ nid }}/"> {% csrf_token %} {{ mf.as_p }} <input type="submit" value="提交"/> </form> </body> </html>
- 生成HTML标签:class Meta
- mf = xxxModelForm(instance=ModelObj)
- 额外的标签, is_rmb = Ffields.CharField(widget=Fwidgets.CheckboxInput())
- 各种验证 is_valid() -> 各种钩子
- mf.save()
# 或
instance = mf.save(False)
instance.save()
mf.save_m2m()
时间: 2024-11-05 13:40:13