前言
之前我们在做数据库操作的时候,用的是models组件,而做form验证的时候用的是Form组件.这两个组件都有各自的适用场景,但也有明显的缺点.
Django为我们提供了另一个非常强大的组件:ModelForm.
ModelForm,一看名字我们大概也能猜到它的作用.ModelForm是Model和Form的结合体,顾名思义:ModelForm即可以做验证,也可以做数据库操作.
一.Model和Form回顾
这两篇文章中记录了一些Model和Form的操作:
python Django学习(8)——数据库操作整理
python Django学习(17)——Form组件验证
二.ModelForm
views.py
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
from django import forms
from django.forms import widgets as Fwidgets
from django.forms import fields as Ffields
# Create your views here.
class UserInfoModelForm(forms.ModelForm):
class Meta: # 注:Meta中的每一句都不能加逗号
model = models.UserInfo # 与models建立了依赖关系,这里的UserInfo就是models.py中的UserInfo
fields = '__all__' # fields:如果是__all__就表示列出所有字段
# fields = ['username'] # 这样的话只显示usernanem
# exclude = ['username'] # 这样是排除username,剩下的都显示
labels = {
'username':'用户名',
'email':'邮箱'
} # label就是input框前面的label
help_texts={
'username':'...'
} # 是提示信息
widgets = {
# 'username':Fwidgets.Textarea(attrs={'class':'c1'})
}
error_messages = {
'__all__':{
}, # 定义整体的错误信息
'email': {
'required': '邮箱不能为空',
'invalid': '邮箱格式错误..',
}
} # 定义错误信息
field_classes = {
# 'email':Ffields.URLField # 这里因为是field_classes,所以只能填类,要是加上括号就成对象了,就会报错
}
# 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() # 把form提交的正确的数据全部保存到数据库中
# 下面这三句代码和obj.save这一句代码是一样的
# instance = obj.save(False)
# instance.save()
# obj.save_m2m()
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',on_delete=models.CASCADE)
u2g = models.ManyToManyField(UserGroup)
user_list.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul>
{% for row in li %}
<li>{{ row.username }} - {{ row.user_type.caption }} - <a href="/app01/edit-{{ row.id }}/">编辑</a></li>
{% endfor %}
</ul>
</body>
</html>
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<form action="/app01/index/" method="post">
{% csrf_token %}
{{ obj.as_p }}
<input type="submit" value="提交">
</form>
</body>
</html>
user_edit.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>user_edit</title>
</head>
<body>
<form method="POST" action="/edit-{{ nid }}/">
{% csrf_token %}
{{ mf.as_p }}
<input type="submit" value="提交" />
</form>
</body>
</html>
url.py:
from django.urls import path,re_path
from app01 import views
urlpatterns = [
path('index/', views.index),
path('user_list/', views.user_list),
re_path('edit-(\d+)/', views.user_edit),
]
urls.py:
"""day24 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
urlpatterns = [
path('admin/', admin.site.urls),
path('app01/', include('app01.url')),
]
写在最后
本文是个人的一些学习笔记,如有侵权,请及时联系我进行删除,谢谢大家.