表单-modelform

ModelForm:

大家在写表单的时候,会发现表单中的Field和模型中的Field基本上是一模一样的,而且表单中需要验证的数据,也就是我们模型中需要保存的。那么这时候我们就可以将模型中的字段和表单中的字段进行绑定。
比如现在有个Article的模型。示例代码如下:

from django.db import models
from django.core import validators
class Article(models.Model):
    title = models.CharField(max_length=10,validators=[validators.MinLengthValidator(limit_value=3)])
    content = models.TextField()
    author = models.CharField(max_length=100)
    category = models.CharField(max_length=100)
    create_time = models.DateTimeField(auto_now_add=True)

那么在写表单的时候,就不需要把Article模型中所有的字段都一个个重复写一遍了。示例代码如下:

from django import forms
class MyForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = "__all__"

MyForm是继承自forms.ModelForm,然后在表单中定义了一个Meta类,在Meta类中指定了model=Article,以及fields="__all__",这样就可以将Article模型中所有的字段都复制过来,进行验证。如果只想针对其中几个字段进行验证,那么可以给fields指定一个列表,将需要的字段写进去。比如只想验证titlecontent,那么可以使用以下代码实现:

from django import forms
class MyForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = [‘title‘,‘content‘]

如果要验证的字段比较多,只是除了少数几个字段不需要验证,那么可以使用exclude来代替fields。比如我不想验证category,那么示例代码如下:

class MyForm(forms.ModelForm):
    class Meta:
        model = Article
        exclude = [‘category‘]

自定义错误消息:

使用ModelForm,因为字段都不是在表单中定义的,而是在模型中定义的,因此一些错误消息无法在字段中定义。那么这时候可以在Meta类中,定义error_messages,然后把相应的错误消息写到里面去。示例代码如下:

class MyForm(forms.ModelForm):
    class Meta:
        model = Article
        exclude = [‘category‘]
        error_messages  ={
            ‘title‘:{
                ‘max_length‘: ‘最多不能超过10个字符!‘,
                ‘min_length‘: ‘最少不能少于3个字符!‘
            },
            ‘content‘: {
                ‘required‘: ‘必须输入content!‘,
            }
        }

save方法:

ModelForm还有save方法,可以在验证完成后直接调用save方法,就可以将这个数据保存到数据库中了。示例代码如下:

form = MyForm(request.POST)
if form.is_valid():
    form.save()
    return HttpResponse(‘succes‘)
else:
    print(form.get_errors())
    return HttpResponse(‘fail‘)

这个方法必须要在clean没有问题后才能使用,如果在clean之前使用,会抛出异常。另外,我们在调用save方法的时候,如果传入一个commit=False,那么只会生成这个模型的对象,而不会把这个对象真正的插入到数据库中。比如表单上验证的字段没有包含模型中所有的字段,这时候就可以先创建对象,再根据填充其他字段,把所有字段的值都补充完成后,再保存到数据库中。示例代码如下:

form = MyForm(request.POST)
if form.is_valid():
    article = form.save(commit=False)
    article.category = ‘Python‘
    article.save()
    return HttpResponse(‘succes‘)
else:
    print(form.get_errors())
    return HttpResponse(‘fail‘)

*:first-child {
margin-top: 0 !important;
}

.markdown-body>*:last-child {
margin-bottom: 0 !important;
}

.markdown-body .headeranchor-link {
position: absolute;
top: 0;
bottom: 0;
left: 0;
display: block;
padding-right: 6px;
padding-left: 30px;
margin-left: -30px;
}

.markdown-body .headeranchor-link:focus {
outline: none;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
position: relative;
margin-top: 1em;
margin-bottom: 16px;
font-weight: bold;
line-height: 1.4;
}

.markdown-body h1 .headeranchor,
.markdown-body h2 .headeranchor,
.markdown-body h3 .headeranchor,
.markdown-body h4 .headeranchor,
.markdown-body h5 .headeranchor,
.markdown-body h6 .headeranchor {
display: none;
color: #000;
vertical-align: middle;
}

.markdown-body h1:hover .headeranchor-link,
.markdown-body h2:hover .headeranchor-link,
.markdown-body h3:hover .headeranchor-link,
.markdown-body h4:hover .headeranchor-link,
.markdown-body h5:hover .headeranchor-link,
.markdown-body h6:hover .headeranchor-link {
height: 1em;
padding-left: 8px;
margin-left: -30px;
line-height: 1;
text-decoration: none;
}

.markdown-body h1:hover .headeranchor-link .headeranchor,
.markdown-body h2:hover .headeranchor-link .headeranchor,
.markdown-body h3:hover .headeranchor-link .headeranchor,
.markdown-body h4:hover .headeranchor-link .headeranchor,
.markdown-body h5:hover .headeranchor-link .headeranchor,
.markdown-body h6:hover .headeranchor-link .headeranchor {
display: inline-block;
}

.markdown-body h1 {
padding-bottom: 0.3em;
font-size: 2.25em;
line-height: 1.2;
border-bottom: 1px solid #eee;
}

.markdown-body h2 {
padding-bottom: 0.3em;
font-size: 1.75em;
line-height: 1.225;
border-bottom: 1px solid #eee;
}

.markdown-body h3 {
font-size: 1.5em;
line-height: 1.43;
}

.markdown-body h4 {
font-size: 1.25em;
}

.markdown-body h5 {
font-size: 1em;
}

.markdown-body h6 {
font-size: 1em;
color: #777;
}

.markdown-body p,
.markdown-body blockquote,
.markdown-body ul,
.markdown-body ol,
.markdown-body dl,
.markdown-body table,
.markdown-body pre,
.markdown-body .admonition {
margin-top: 0;
margin-bottom: 16px;
}

.markdown-body hr {
height: 4px;
padding: 0;
margin: 16px 0;
background-color: #e7e7e7;
border: 0 none;
}

.markdown-body ul,
.markdown-body ol {
padding-left: 2em;
}

.markdown-body ul ul,
.markdown-body ul ol,
.markdown-body ol ol,
.markdown-body ol ul {
margin-top: 0;
margin-bottom: 0;
}

.markdown-body li>p {
margin-top: 16px;
}

.markdown-body dl {
padding: 0;
}

.markdown-body dl dt {
padding: 0;
margin-top: 16px;
font-size: 1em;
font-style: italic;
font-weight: bold;
}

.markdown-body dl dd {
padding: 0 16px;
margin-bottom: 16px;
}

.markdown-body blockquote {
padding: 0 15px;
color: #777;
border-left: 4px solid #ddd;
}

.markdown-body blockquote>:first-child {
margin-top: 0;
}

.markdown-body blockquote>:last-child {
margin-bottom: 0;
}

.markdown-body table {
display: block;
width: 100%;
overflow: auto;
word-break: normal;
word-break: keep-all;
}

.markdown-body table th {
font-weight: bold;
}

.markdown-body table th,
.markdown-body table td {
padding: 6px 13px;
border: 1px solid #ddd;
}

.markdown-body table tr {
background-color: #fff;
border-top: 1px solid #ccc;
}

.markdown-body table tr:nth-child(2n) {
background-color: #f8f8f8;
}

.markdown-body img {
max-width: 100%;
-moz-box-sizing: border-box;
box-sizing: border-box;
}

.markdown-body code,
.markdown-body samp {
padding: 0;
padding-top: 0.2em;
padding-bottom: 0.2em;
margin: 0;
font-size: 85%;
background-color: rgba(0,0,0,0.04);
border-radius: 3px;
}

.markdown-body code:before,
.markdown-body code:after {
letter-spacing: -0.2em;
content: "\00a0";
}

.markdown-body pre>code {
padding: 0;
margin: 0;
font-size: 100%;
word-break: normal;
white-space: pre;
background: transparent;
border: 0;
}

.markdown-body .codehilite {
margin-bottom: 16px;
}

.markdown-body .codehilite pre,
.markdown-body pre {
padding: 16px;
overflow: auto;
font-size: 85%;
line-height: 1.45;
background-color: #f7f7f7;
border-radius: 3px;
}

.markdown-body .codehilite pre {
margin-bottom: 0;
word-break: normal;
}

.markdown-body pre {
word-wrap: normal;
}

.markdown-body pre code {
display: inline;
max-width: initial;
padding: 0;
margin: 0;
overflow: initial;
line-height: inherit;
word-wrap: normal;
background-color: transparent;
border: 0;
}

.markdown-body pre code:before,
.markdown-body pre code:after {
content: normal;
}

/* Admonition */
.markdown-body .admonition {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
position: relative;
border-radius: 3px;
border: 1px solid #e0e0e0;
border-left: 6px solid #333;
padding: 10px 10px 10px 30px;
}

.markdown-body .admonition table {
color: #333;
}

.markdown-body .admonition p {
padding: 0;
}

.markdown-body .admonition-title {
font-weight: bold;
margin: 0;
}

.markdown-body .admonition>.admonition-title {
color: #333;
}

.markdown-body .attention>.admonition-title {
color: #a6d796;
}

.markdown-body .caution>.admonition-title {
color: #d7a796;
}

.markdown-body .hint>.admonition-title {
color: #96c6d7;
}

.markdown-body .danger>.admonition-title {
color: #c25f77;
}

.markdown-body .question>.admonition-title {
color: #96a6d7;
}

.markdown-body .note>.admonition-title {
color: #d7c896;
}

.markdown-body .admonition:before,
.markdown-body .attention:before,
.markdown-body .caution:before,
.markdown-body .hint:before,
.markdown-body .danger:before,
.markdown-body .question:before,
.markdown-body .note:before {
font: normal normal 16px fontawesome-mini;
-moz-osx-font-smoothing: grayscale;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
line-height: 1.5;
color: #333;
position: absolute;
left: 0;
top: 0;
padding-top: 10px;
padding-left: 10px;
}

.markdown-body .admonition:before {
content: "\f056\00a0";
color: 333;
}

.markdown-body .attention:before {
content: "\f058\00a0";
color: #a6d796;
}

.markdown-body .caution:before {
content: "\f06a\00a0";
color: #d7a796;
}

.markdown-body .hint:before {
content: "\f05a\00a0";
color: #96c6d7;
}

.markdown-body .danger:before {
content: "\f057\00a0";
color: #c25f77;
}

.markdown-body .question:before {
content: "\f059\00a0";
color: #96a6d7;
}

.markdown-body .note:before {
content: "\f040\00a0";
color: #d7c896;
}

.markdown-body .admonition::after {
content: normal;
}

.markdown-body .attention {
border-left: 6px solid #a6d796;
}

.markdown-body .caution {
border-left: 6px solid #d7a796;
}

.markdown-body .hint {
border-left: 6px solid #96c6d7;
}

.markdown-body .danger {
border-left: 6px solid #c25f77;
}

.markdown-body .question {
border-left: 6px solid #96a6d7;
}

.markdown-body .note {
border-left: 6px solid #d7c896;
}

.markdown-body .admonition>*:first-child {
margin-top: 0 !important;
}

.markdown-body .admonition>*:last-child {
margin-bottom: 0 !important;
}

/* progress bar*/
.markdown-body .progress {
display: block;
width: 300px;
margin: 10px 0;
height: 24px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #ededed;
position: relative;
box-shadow: inset -1px 1px 3px rgba(0, 0, 0, .1);
}

.markdown-body .progress-label {
position: absolute;
text-align: center;
font-weight: bold;
width: 100%; margin: 0;
line-height: 24px;
color: #333;
text-shadow: 1px 1px 0 #fefefe, -1px -1px 0 #fefefe, -1px 1px 0 #fefefe, 1px -1px 0 #fefefe, 0 1px 0 #fefefe, 0 -1px 0 #fefefe, 1px 0 0 #fefefe, -1px 0 0 #fefefe, 1px 1px 2px #000;
-webkit-font-smoothing: antialiased !important;
white-space: nowrap;
overflow: hidden;
}

.markdown-body .progress-bar {
height: 24px;
float: left;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #96c6d7;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .5), inset 0 -1px 0 rgba(0, 0, 0, .1);
background-size: 30px 30px;
background-image: -webkit-linear-gradient(
135deg, rgba(255, 255, 255, .4) 27%,
transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%,
transparent 77%, transparent
);
background-image: -moz-linear-gradient(
135deg,
rgba(255, 255, 255, .4) 27%, transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%, transparent 77%,
transparent
);
background-image: -ms-linear-gradient(
135deg,
rgba(255, 255, 255, .4) 27%, transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%, transparent 77%,
transparent
);
background-image: -o-linear-gradient(
135deg,
rgba(255, 255, 255, .4) 27%, transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%, transparent 77%,
transparent
);
background-image: linear-gradient(
135deg,
rgba(255, 255, 255, .4) 27%, transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%, transparent 77%,
transparent
);
}

.markdown-body .progress-100plus .progress-bar {
background-color: #a6d796;
}

.markdown-body .progress-80plus .progress-bar {
background-color: #c6d796;
}

.markdown-body .progress-60plus .progress-bar {
background-color: #d7c896;
}

.markdown-body .progress-40plus .progress-bar {
background-color: #d7a796;
}

.markdown-body .progress-20plus .progress-bar {
background-color: #d796a6;
}

.markdown-body .progress-0plus .progress-bar {
background-color: #c25f77;
}

.markdown-body .candystripe-animate .progress-bar{
-webkit-animation: animate-stripes 3s linear infinite;
-moz-animation: animate-stripes 3s linear infinite;
animation: animate-stripes 3s linear infinite;
}

@-webkit-keyframes animate-stripes {
0% {
background-position: 0 0;
}

100% {
background-position: 60px 0;
}
}

@-moz-keyframes animate-stripes {
0% {
background-position: 0 0;
}

100% {
background-position: 60px 0;
}
}

@keyframes animate-stripes {
0% {
background-position: 0 0;
}

100% {
background-position: 60px 0;
}
}

.markdown-body .gloss .progress-bar {
box-shadow:
inset 0 4px 12px rgba(255, 255, 255, .7),
inset 0 -12px 0 rgba(0, 0, 0, .05);
}

/* Multimarkdown Critic Blocks */
.markdown-body .critic_mark {
background: #ff0;
}

.markdown-body .critic_delete {
color: #c82829;
text-decoration: line-through;
}

.markdown-body .critic_insert {
color: #718c00 ;
text-decoration: underline;
}

.markdown-body .critic_comment {
color: #8e908c;
font-style: italic;
}

.markdown-body .headeranchor {
font: normal normal 16px octicons-anchor;
line-height: 1;
display: inline-block;
text-decoration: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.headeranchor:before {
content: ‘\f05c‘;
}

.markdown-body .task-list-item {
list-style-type: none;
}

.markdown-body .task-list-item+.task-list-item {
margin-top: 3px;
}

.markdown-body .task-list-item input {
margin: 0 4px 0.25em -20px;
vertical-align: middle;
}

/* Media */
@media only screen and (min-width: 480px) {
.markdown-body {
font-size:14px;
}
}

@media only screen and (min-width: 768px) {
.markdown-body {
font-size:16px;
}
}

@media print {
.markdown-body * {
background: transparent !important;
color: black !important;
filter:none !important;
-ms-filter: none !important;
}

.markdown-body {
font-size:12pt;
max-width:100%;
outline:none;
border: 0;
}

.markdown-body a,
.markdown-body a:visited {
text-decoration: underline;
}

.markdown-body .headeranchor-link {
display: none;
}

.markdown-body a[href]:after {
content: " (" attr(href) ")";
}

.markdown-body abbr[title]:after {
content: " (" attr(title) ")";
}

.markdown-body .ir a:after,
.markdown-body a[href^="javascript:"]:after,
.markdown-body a[href^="#"]:after {
content: "";
}

.markdown-body pre {
white-space: pre;
white-space: pre-wrap;
word-wrap: break-word;
}

.markdown-body pre,
.markdown-body blockquote {
border: 1px solid #999;
padding-right: 1em;
page-break-inside: avoid;
}

.markdown-body .progress,
.markdown-body .progress-bar {
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}

.markdown-body .progress {
border: 1px solid #ddd;
}

.markdown-body .progress-bar {
height: 22px;
border-right: 1px solid #ddd;
}

.markdown-body tr,
.markdown-body img {
page-break-inside: avoid;
}

.markdown-body img {
max-width: 100% !important;
}

.markdown-body p,
.markdown-body h2,
.markdown-body h3 {
orphans: 3;
widows: 3;
}

.markdown-body h2,
.markdown-body h3 {
page-break-after: avoid;
}
}
-->

原文地址:https://www.cnblogs.com/ys-python/p/11285968.html

时间: 2024-10-13 13:10:18

表单-modelform的相关文章

django模型表单ModelForm

如果你正在构建一个数据库驱动的应用,那么你可能会有与Django的模型紧密映射的表单.比如,你有个BlogComment模型,并且你还想创建一个表单让大家提交评论到这个模型中.在这种情况下,写一个forms.Form类,然后在表单类中定义字段,这种一般创建表单的做法是冗余的,因为你已经在ORM模型model中定义了字段的属性和功能,完全没必要重新写一遍字段. 一.核心用法 基于这个原因,Django提供一个辅助类帮助我们利用Django的ORM模型model创建Form. 像下面这样: >>&

会话保持及Form表单--Form表单

Form表单分为三种:Form表单都继承自django.forms 1.简单表单的使用(Form) 2.模型表单(ModelForm) 3.模型表单的自定义验证 实例1:简单表单的使用,博客用户注册 步骤 在项目目录下创建forms.py,表单文件 from django import formsclass RegisterForm(forms.Form): username = forms.CharField(label='用户名',max_length=20) #CharField 默认对应

django03_表单(forms.ModelForm)login后台

一,创建一个表单创建一个Form表单有两种方式:第一种方式是继承于forms.Form,的一个子类,通过在form中选择你需要的类型来规定表单之中字段的类型 class LoginForm(forms.Form):     username = forms.CharField(max_length=15,                                 min_length=5,                                 #onblur = "Check(t

django表单使用forms.ModelForm

win7 python2.7 django 1.6.5 因为使用数据库sqlite,项目中有models.py,所以使用方便的forms.ModelForm处理表单. 上传图像文件使用默认的defaultstorage. 1.settings.py里增加两行media的定义: #Media MEDIA_ROOT = 'e:/Depot/media' MEDIA_URL = '/media/' 2.models.py #coding: utf8 from django.db import mode

Django使用普通表单、Form、以及modelForm操作数据库方式总结

Django使用普通表单.Form.以及modelForm操作数据库主要应用于增删该查的情景下,流程通用如下,只是实现方式不一样: 进入填写表单页面: 在表单页面填写信息,并提交: 表单数据验证 验证成功,和数据库进行交互(增删改查): 验证成功,页面提示表单填写失败: 一.Django使用普通表单操作数据库 1.html代码: <form action="/add/" method="post" name="addbook"> {%

四【用django2.0来开发】后台会员管理(二) ModelForm表单的使用方法以及数据验证

上一节我们讲完了ModelAdmin的使用, 但是在操作中也发现, 新增编辑会员时, 我们无法验证数据是否正确, 比如 用户名.手机号.邮箱都应该是唯一的 用户名和密码长度的验证 编辑用户信息时不填写密码则不更新密码, 填写了则更新密码 自定义验证不通过的文案... 这些要求, 我们就必须得使用自定义的表单来完成了 项目地址:https://gitee.com/ccnv07/django_example Form介绍 通过表单, 我们可以实现以下的功能 自定义字段的样式 类似的表单可以通过类继承

17.Django表单验证

Django提供了3中方式来验证表单 官网文档:https://docs.djangoproject.com/en/1.9/ref/validators 1.表单字段验证器 a.引入:from django.core.exceptions import ValidationError b.定义验证方法,验证不通过抛一个ValidationError异常 def validate_name(value): 验证不通过 raise ValidationError("%s的信息已经存在"%v

16.Django提交表单

Django表单提交一共有三种方式: 1.不使用Django组件进行提交 2.使用django.forms.Form(所有表单类的父类)进行提交 3.使用django.forms.ModelForm(可以和模型绑定的Form)进行提交 这里的例子是,给Publisher这个表里添加数据,表结构如下: class Publisher(models.Model): name = models.CharField("名称",max_length=30) address = models.Ch

基于model的form表单

Django 提供一个辅助类来让你可以从Django 的模型创建表单.生成的表单类中将具有和指定的模型字段对应的表单字段,顺序为fields 属性中指定的顺序. ForeignKey 和 ManyToManyField 字段类型 ForeignKey 表示成django.forms.ModelChoiceField,它是一个ChoiceField,其选项是模型的查询集. ManyToManyField 表示成django.forms.ModelMultipleChoiceField,它是一个Mu