Django之ModelForm(一)
要说ModelForm,那就先说Form吧!
先给出一个Form示例:
models.py from django.db import models 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(verbose_name="用户",max_length=32) email=models.EmailField() user_type=models.ForeignKey(to='UserType',to_field="id",on_delete=models.CASCADE) #关联UserType 一对一 u2g=models.ManyToManyField(UserGroup) #关联UserGroup 多对多 views.py from django.shortcuts import render from django import forms from django.forms import fields from app_01 import models class UserInfoForm(forms.Form): username = fields.CharField(max_length=32) email = fields.EmailField() user_type = fields.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=UserInfoForm() return render(request,"index.html",{'obj':obj}) elif request.method=="POST": obj=UserInfoForm(request.POST) if obj.is_valid() : obj.save() #验证成功 把所有的正确信息保存在数据库中 return render(request,'index.html',{'obj':obj}) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/index/" method="post"> {{ obj.as_p}} {% csrf_token %} <input type="submit" value="提交" /> </form> </body> </html>
在html上显示的效果为:
看了上面的示例,觉不觉得特麻烦?那让我们现在用ModelForm来实现吧!
其他不用改,只改views.py文件
from django.shortcuts import render from django import forms from django.forms import fields from app_01 import models class UserInfoModelForm(forms.ModelForm): class Meta: model=models.UserInfo fields="__all__" #代指所有的字段
# models.UserInfo.objects.create(**obj.cleaned_data) #在数据库中自动进行创建
# models.UserInfo.objects.filter(id=1).update(**obj.cleaned_data) #在数据库中自动进行更新
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() #验证成功 把所有的正确信息保存在数据库中 return render(request,'index.html',{'obj':obj})
可以看到Form和ModelForm的区别了吧!
但是ModelForm也有弊端的,只能用它写小一点的程序,而大程序利用这个则不适用!
利用ModelForm来实践下吧!
Models.py from django.db import models 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(verbose_name="用户",max_length=32) email=models.EmailField() user_type=models.ForeignKey(to='UserType',to_field="id",on_delete=models.CASCADE) u2g=models.ManyToManyField(UserGroup) Views.py def user_list(request): li=models.UserInfo.objects.all().select_related('user_type') #可以拿到UserInfo表内的数据,也可以拿到UserType表内的数据 return render(request,'user_list.html',{'li':li}) def user_edit(request,nid): if request.method=="GET": user_obj=models.UserInfo.objects.filter(id=nid).first() mf=UserInfoModelForm(instance=user_obj) #这里不能瞎传 必须得有参数 instance 若无instance 则是在数据库内创建了一条数据,而不是直接对数据进行更改 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}) 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 action="/edit-{{ nid }}/" method="post"> {% csrf_token %} {{ mf.as_p }} <input type="submit" value="提交" /> </form> </body> </html> urls.py from django.contrib import admin from django.urls import path from app_01 import views from django.conf.urls import url import re urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), path('user_list/', views.user_list), url(r'^edit-(\d+)/', views.user_edit) #正则表达式 ]
user_list上的操作效果为:
user_erit上的操作效果为