前一章节介绍了
django
中的表单,本章节继续介绍表单,但是本章节是基于数据模型来使用的表单,因为我们也称之为模型表单
一、使用模型表单的主要步骤
-
1、定义数据模型
from django.db import modelsfrom django.core import validatorsclass ArticleModel(models.Model): """ 定义文章的数据模型 """ title = models.CharField(max_length=10, validators=[validators.MinValueValidator(limit_value=3)], verbose_name='标题') content = models.TextField(verbose_name='内容') author = models.CharField(max_length=10, verbose_name='作者') category = models.CharField(max_length=10, verbose_name='分类') create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') update_time = models.DateTimeField(auto_now=True, verbose_name='修改时间') class Meta(object): db_table = 'article'复制代码
-
2、在
app
下面创建一个forms.py
的文件 -
3、在
forms.py
文件中使用模型表单from django import formsfrom . import modelsclass ArticleForms(forms.ModelForm): """ 文章的form模型 """ class Meta(object): model = models.ArticleModel fields = '__all__'复制代码
-
4、视图中使用
from django.shortcuts import renderfrom django.views import Viewfrom django.http import HttpResponsefrom . import formsfrom . import modelsclass ArticleView(View): """ 文章视图 """ def get(self, request, *args, **kwargs): form = forms.ArticleForms() return render(request, 'article.html', context={ 'form': form}) def post(self, request, *args, **kwargs): form = forms.ArticleForms(request.POST) if form.is_valid(): print('表单校验成功') title = form.cleaned_data.get('title') content = form.cleaned_data.get('content') author = form.cleaned_data.get('author') category = form.cleaned_data.get('category') print(title, content, author, category) return HttpResponse('成功') else: print('表单校验失败') print(form.get_errors()) return HttpResponse('失败')复制代码
-
5、前端
html
页面
二、关于模型表单别的知识点的补充
-
1、如果要使用全部的字段就在
fields
中使用__all__
class ArticleForms(forms.ModelForm): """ 文章的form模型 """ class Meta(object): model = models.ArticleModel fields = '__all__'复制代码
-
2、如果是需要显示某些字段的时候
class ArticleForms(forms.ModelForm): """ 文章的form模型 """ class Meta(object): model = models.ArticleModel fields = ['title', 'content']复制代码
-
3、如果模型中字段比较多使用排除的方法
class ArticleForms(forms.ModelForm): """ 文章的form模型 """ class Meta(object): model = models.ArticleModel # fields = ['title', 'content'] exclude = ['title']复制代码
三、关于错误信息的处理
之前是写在每一个字段上,现在没字段可写了
-
1、直接在
forms.py
中定义class ArticleForms(forms.ModelForm): """ 文章的form模型 """ class Meta(object): model = models.ArticleModel fields = '__all__' error_messages = { 'title': { 'max_length': 'title字段不能超过10字符', 'required': '请输入标题', 'invalid': '请输入一个有效的标题' } }复制代码
-
2、可以在
models
中给某一个字段添加from django.core import validatorsclass ArticleModel(models.Model): """ 定义文章的数据模型 """ title = models.CharField(max_length=10, validators=[validators.MinValueValidator(limit_value=3)], verbose_name='标题') 复制代码
-
3、在
forms.py
中定义一个方法class ArticleForms(forms.ModelForm): """ 文章的form模型 """ class Meta(object): model = models.ArticleModel fields = '__all__' def clean_price(self): """ 自定义价格的校验 :return: """ price = self.cleaned_data.get('price') if price < 0: raise forms.ValidationError('价格不能不能小于0元') return price复制代码
四、关于表单中save
的方法
-
1、直接使用
save
保存数据class ArticleView(View): """ 文章视图 """ def get(self, request, *args, **kwargs): form = forms.ArticleForms() return render(request, 'article.html', context={ 'form': form}) def post(self, request, *args, **kwargs): form = forms.ArticleForms(request.POST) if form.is_valid(): print('表单校验成功') form.save() return HttpResponse('成功') else: print('表单校验失败') print(form.get_errors()) return HttpResponse('失败')复制代码
-
2、当遇到模型中字段与表单中字段不一致的时候
# 模型字段class UserModel(models.Model): username = models.CharField(max_length=100, verbose_name='用户名') password = models.CharField(max_length=100, verbose_name='密码') class Meta(object): db_table = 'c_user'复制代码
# 表单校验的class RegisterForm(forms.ModelForm): pwd1 = forms.CharField(max_length=100, min_length=2) pwd2 = forms.CharField(max_length=100, min_length=2) def clean(self): cleaned_data = super().clean() pwd1 = cleaned_data.get('pwd1') pwd2 = cleaned_data.get('pwd2') if pwd1 !=pwd2: raise forms.ValidationError('两次密码不一致') return cleaned_data class Meta(object): model = models.UserModel exclude = ['password']复制代码
# 视图中使用class RegisterView(View): """ 用户注册 """ def get(self, request, *args, **kwargs): form = forms.RegisterForm() return render(request, 'register.html', context={ 'form': form}) def post(self, request, *args, **kwargs): form = forms.RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.password = form.cleaned_data.get('pwd1') user.save() return HttpResponse('成功') else: print(form.get_errors()) return HttpResponse('失败')复制代码