模型表单定义
from django.db import models
# Create your models here.
class Author(models.Model):
name = models.CharField(max_length=25) # 名字
email = models.CharField(max_length=50) # 邮箱
def __str__(self):
return self.name
class Editor(models.Model):
headline = models.CharField(max_length=255) # 标题
body_text = models.TextField() # 文本
author = models.ManyToManyField(Author) #作者
def __str__(self):
return self.headline
迁移
(class15env) PS D:\muyi\Django\muyi> python ./manage.py makemigrations
Migrations for 'the_13':
the_13\migrations\0001_initial.py
- Create model Author
- Create model Editor
(class15env) PS D:\muyi\Django\muyi> python .\manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, the_10, the_13, the_5, the_7, the_8, the_9
Running migrations:
Applying the_13.0001_initial... OK
创建表单
form.py
from django . forms import ModelForm
from the_13.models import Author
class AuthorForm(ModelForm):
class Meta:
model = Author # 模型表单关联
# fields = ['name','email'] # 获取指定字段
fields = '__all__' # 获取所有字段
exclude = ['email'] # 排除字段
模型字段与表单字段的对应
▶
字段对应表
▶
ForeignKey -> forms.ModelChoiceField
▶
ManyToManyField -> forms.ModelMultipleChoiceField
▶
blank=True -> required=False
▶
verbose_name -> label
▶
help_text -> help_text
views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from the_13.forms import AuthorForm
# Create your views here.
def hello(request):
return HttpResponse("hello word")
class HelloView(View):
def get(self, request):
form = AuthorForm()
return render(request, "the_13/helloview.html", {'myform': form})
def post(self, request):
form = AuthorForm(request.POST)
if form.is_valid():
print('校验后的数据', form.cleaned_data)
else:
print(form.errors)
return render(request, "the_13/helloview.html", {'post': True})
urls.py
from django.urls import path
from .views import hello, HelloView
app_name = 'the_13' # 命名空间
urlpatterns = [
path('Hello/', hello),
path('HelloView/', HelloView.as_view(), name='form_Hello'),
]
helloview.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>模型表单</h1>
<form action="{% url 'the_13:form_Hello' %}" method="post">
{{ myform }}
<input type="submit" value="提交">
</form>
{% if post %}
<div>这是 post 请求</div>
{% endif %}
</body>
</html>
模型表单验证
from django.forms import ModelForm, forms
from the_13.models import Author
class AuthorForm(ModelForm):
class Meta:
model = Author # 模型表单关联
# fields = ['name','email'] # 获取指定字段
fields = '__all__' # 获取所有字段
# exclude = ['email'] # 排除字段
# 校验
def clean_name(self):
name = self.cleaned_data.get('name','')
if not name.startswith('hk'):
raise forms.ValidationError('必须要以hk开头才可以')
return name
def clean_email(self):
email = self.cleaned_data.get('email','')
return email
模型表单的存库
校验好的数据.save() 提交即可
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from the_13.forms import AuthorForm
# Create your views here.
def hello(request):
return HttpResponse("hello word")
class HelloView(View):
def get(self, request):
form = AuthorForm()
return render(request, "the_13/helloview.html", {'myform': form})
def post(self, request):
form = AuthorForm(request.POST)
if form.is_valid():
print('校验后的数据', form.cleaned_data)
form.save() # 提交
else:
print(form.errors)
return render(request, "the_13/helloview.html", {'post': True})
ArticleForm(request.POST, instance=a)
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from the_13.forms import AuthorForm
from the_13.models import Author
# Create your views here.
def hello(request):
return HttpResponse("hello word")
class HelloView(View):
def get(self, request):
form = AuthorForm()
return render(request, "the_13/helloview.html", {'myform': form})
def post(self, request):
# 利用模型表单进行修改
author = Author.objects.get(id=1)
form = AuthorForm(request.POST, instance=author) # instance 更新的意思
if form.is_valid():
print('校验后的数据', form.cleaned_data)
form.save() # 提交
else:
print(form.errors)
return render(request, "the_13/helloview.html", {'post': True})
save(commit=False)
save_m2m()
class M2M(View):
def get(self, request):
form = M2MForm()
return render(request, "the_13/M2M.html", {'myform': form})
def post(self, request):
form = M2MForm(request.POST)
if form.is_valid():
print('校验后的数据', form.cleaned_data)
entry = form.save(commit=False)
entry.headline = 'django框架'
form.save() # 提交
else:
print(form.errors)
return render(request, "the_13/M2M.html", {'post': True})
forms.py
class M2MForm(ModelForm):
class Meta:
model = Editor
fields = '__all__'
M2M.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>保存多表关系</h1>
<form action="{% url 'the_13:form_M2M' %}" method="post">
{{ myform }}
<input type="submit" value="提交">
</form>
{% if post %}
<div>这是 post 请求</div>
{% endif %}
</body>
modelform_factory
# class M2MForm(ModelForm):
# class Meta:
# model = Editor
# fields = '__all__'
# # exclude = ['headline'] # 排除
# 优化
M2MForm = modelform_factory(Editor, fields='__all__')