二十三. Django ModelForm组件

一.  Django ModelForm组件

https://download.csdn.net/download/baobao267/10722491   Django之Form表单验证及Ajax验证方式汇总

https://www.jianshu.com/p/1c65fa4a6ca7  ModelForm和form区别使用

https://blog.csdn.net/weixin_34179762/article/details/93371564    ModelForm操作及验证

 

首先导入ModelForm

from django.forms import ModelForm
在视图函数中,定义一个类,比如就叫StudentList,这个类要继承ModelForm,在这个类中再写一个原类Meta(规定写法,并注意首字母是大写的)

在这个原类中,有以下属性(部分)
class StudentList(ModelForm):
    class Meta:
        model = models.Student  #对应的Model中的类
        fields = "__all__"      #字段,如果是__all__,就是表示列出所有的字段
        exclude = None          #排除的字段
        labels = None           #提示信息
        help_texts = None       #帮助提示信息
        widgets = None          #自定义插件
        error_messages = None   #自定义错误信息
#error_messages用法:
        error_messages = {
            'name':{'required':"用户名不能为空",},
            'age':{'required':"年龄不能为空",},
        }

#widgets用法,比如把输入用户名的input框给为Textarea
#首先得导入模块
        from django.forms import widgets as wid  #因为重名,所以起个别名
        widgets = {
            "name":wid.Textarea(attrs={"class":"c1"}) #还可以自定义属性
        }
#labels,自定义在前端显示的名字

    labels= {
            "name":"用户名"
        }

二. ModelForm使用案例

https://www.cnblogs.com/hnlmy/p/9526720.html   案例

model

from django.db import models

# Create your models here.

class Book(models.Model):

    title=models.CharField(max_length=32)
    price=models.DecimalField(max_digits=8,decimal_places=2)  # 999999.99
    date=models.DateField()
    publish=models.ForeignKey("Publish",on_delete=models.CASCADE)
    authors=models.ManyToManyField("Author")
    def __str__(self):
        return self.title



class Publish(models.Model):
    name=models.CharField(max_length=32)
    def __str__(self):
        return self.name

class Author(models.Model):
    name=models.CharField(max_length=32)
    def __str__(self):
        return self.name
views

from django.shortcuts import render,redirect
# Create your views here.

from .models import *
from django import forms
from django.forms import widgets

from django.forms import ModelForm

'''
class BookForm(forms.Form):

        email=forms.EmailField()
        title = forms.CharField(max_length=32,label="书籍名称")
        price = forms.DecimalField(max_digits=8, decimal_places=2,label="价格")  # 999999.99
        date = forms.DateField(label="日期",
            widget=widgets.TextInput(attrs={"type":"date"})
        )
        #gender=forms.ChoiceField(choices=((1,"男"),(2,"女"),(3,"其他")))
        #publish=forms.ChoiceField(choices=Publish.objects.all().values_list("pk","title"))
        publish=forms.ModelChoiceField(queryset=Publish.objects.all())
        authors=forms.ModelMultipleChoiceField(queryset=Author.objects.all())
'''

from django.forms import widgets as wid
class BookForm(ModelForm):

    class Meta:
        model=Book
        fields="__all__"    # 对Book表中所有字段转换渲染到页面上
        # fields = ["title","price"]   # 对Book表中title price字段转换渲染到页面上

        labels={"title":"书籍名称:", "price":"价格:"}

        widgets={
            "title":wid.TextInput(attrs={"class":"form-control"}),
            "price":wid.TextInput(attrs={"class":"form-control"}),
            "date":wid.TextInput(attrs={"class":"form-control","type":"date"}),
            "publish":wid.Select(attrs={"class":"form-control"}),
            "authors":wid.SelectMultiple(attrs={"class":"form-control"}),
        }
        error_messages={
            "title":{"required":"不能为空"}
        }


def books(request):
    book_list=Book.objects.all()
    return render(request,"books.html",locals())

def addbook(request):
    if request.method=="POST":
        form = BookForm(request.POST)
        if form.is_valid():
            form.save()    # form.model.objects.create(request.POST)    保存添加的数据到mysql中
            return redirect("/books/")
        else:
            return render(request, "add.html", locals())
    form=BookForm()
    return render(request,"add.html",locals())




def editbook(request,edit_book_id):
    edit_book = Book.objects.filter(pk=edit_book_id).first()
    if request.method=="POST":
        form = BookForm(request.POST,instance=edit_book)   # 意思想要编辑的对象
        if form.is_valid():
            form.save()  # edit_book.update(request.POST)  编辑编辑跟新
            return redirect("/books/")
    form=BookForm(instance=edit_book)
    return render(request,"edit.html",locals())
templates
form.html

<form action="" method="post" novalidate>
      {% csrf_token %}
      {% for field in form %}
        <div>
         {{ field.label }}
         {{ field }} <span>{{ field.errors.0 }}</span>
        </div>
      {% endfor %}
    <input type="submit">
</form>
books.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<a href="/book/add"><button>添加书籍</button></a>
<hr>
<table border="1">
    {% for book in book_list %}
       <tr>
           <td>{{ book.title }}</td>
           <td>{{ book.price }}</td>
           <td>{{ book.date|date:"Y-m-d" }}</td>
           <td>{{ book.publish.name }}</td>
           <td>{{ book.authors.all }}</td>
            <td><a href="/book/edit/{{book.pk}}"><button>编辑</button></a></td>
       </tr>
    {% endfor %}

</table>


</body>
</html>
add.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>

<h3>添加页面</h3>
<div class="row">
    <div class="col-md-4 col-md-offset-3">
        {% include 'form.html' %}
    </div>
</div>

</body>
</html>
edit.html


<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<h3>编辑页面</h3>

{% include 'form.html' %}
</body>
</html>

 

  

 

 

 

 

转载于:https://www.cnblogs.com/lovershowtime/p/11568040.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值