Django的ModelForm

Posted zgf-666

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django的ModelForm相关的知识,希望对你有一定的参考价值。

这个组件的功能就是把model和form组合起来

1.创建ModelForm


1.model.py中创建模型表

class Book(models.Model):
    title=models.CharField(max_length=32)
    price=models.DecimalField(max_digits=8,decimal_places=2)
    pub_date=models.DateField()
    publish=models.ForeignKey("Publish")
    authors=models.ManyToManyField("Author")

    def __str__(self):
        return self.title

 

2.首先导入ModelForm

from django.forms import ModelForm在视图函数中,定义一个类,比如就叫SBookModelForm,这个类要继承ModelForm,在这个类中再写一个原类Meta(规定写法,并注意首字母是大写的)
class BookModelForm(ModelForm):
    class Meta:
        1.#对应的Model中的类,对哪张表设置,就写哪张表
        model=models.Book
        2.#校验的字段
        #fields=["title","price","pub_date"]
        fields="__all__"
        3.自定义错误提示:
         error_messages = {
        name:{required:"用户名不能为空",},
        age:{required:"年龄不能为空",},
        }
        4.#widgets用法,比如把输入用户名的input框给为Textarea
        from django.forms import widgets as wid #因为重名,所以起个别名
          widgets={
            "pub_date":wid.TextInput(attrs={"type":"date"})
        }
        5.labels,自定义在前端显示的名字
         labels= {
                "name":"用户名",
                "price":"价格"
        }
        def clean_title(self):
             return self.cleaned_data.get("title")

2.基于ModelForm添加数据

def addbook(request):
    if request.method=="POST":

        form=BookModelForm(request.POST)
        if form.is_valid():

            form.save() # create方法  :BookModelForm.Meta.model.objects.create(**form.cleaned_data)   

            return redirect("/books/")
        else:
            return render(request, "addbook.html", locals())

    form=BookModelForm()
    return render(request,"addbook.html",locals())
addbook.html:      
  <form action="" method="post" novalidate>
    {% csrf_token %}

    {% for field in form %}
    <p>
        <label for="">{{ field.label }}</label>
        {{ field }} <span>{{ field.errors.0 }}</span>
    </p>
    {% endfor %}
    <input type="submit">
</form>

3.基于ModelForm编辑数据 (instance)

def changebook(request,id):
    edit_book = models.Book.objects.get(pk=id)
    if request.method=="POST":  
        form = BookModelForm(request.POST,instance=edit_book)
        if form.is_valid():
            form.save()  # update方法:  edit_book.update(form.cleaned_data)
            return redirect("/books/")
        else:
            return render(request, "addbook.html", locals())
    form=BookModelForm(instance=edit_book)
    return render(request,"changebook.html",locals())
changebook.html:

HTML

changebook.html:
<form action="" method="post">
    {% csrf_token %}

    {{ form.as_p }}

    <input type="submit">
</form>

基于ModelForm的图书管理系统

技术分享图片
from django.forms import ModelForm

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

from django.forms import widgets as wid

class BookModelForm(ModelForm):
    class Meta:
        model=models.Book
        #fields=["title","price","pub_date"]
        fields="__all__"
        labels={"title":"书籍名称","price":"价格"}
        error_messages={
            "title":{required:"书籍名称不能为空",}
        },
        widgets={
            "pub_date":wid.TextInput(attrs={"type":"date"})
        }
    def clean_title(self):
        return self.cleaned_data.get("title")

def addbook(request):
    if request.method=="POST":
        form=BookModelForm(request.POST)
        if form.is_valid():

            form.save() # create方法

            return redirect("/books/")
        else:
           return render(request, "addbook.html", locals())
    form=BookModelForm()
    return render(request,"addbook.html",locals())

def changebook(request,id):
    if request.method=="POST":
        edit_book = models.Book.objects.get(pk=id)
        form = BookModelForm(request.POST,instance=edit_book)
        if form.is_valid():
            form.save()  # update方法  edit_book.update(request.POST)
            return redirect("/books/")
        else:
            return render(request, "addbook.html", locals())
    edit_book=models.Book.objects.get(pk=id)
    form=BookModelForm(instance=edit_book)
    return render(request,"changebook.html",locals())

def deletebook(request,id):
    models.Book.objects.get(pk=id).delete()
    return redirect("/books/")
Views.py
技术分享图片
‘‘‘
book_list
<ul>
    {% for book in book_list %}
    <li>{{ book.title }}---{{ book.price }}-----{{ book.publish.name }}
        <a href="/books/{{ book.pk }}/change/">编辑</a>
        <a href="/books/{{ book.pk }}/delete/">删除</a>
    </li>
    {% endfor %}
</ul>
changebook
<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit">
</form>
addbook
<form action="" method="post" novalidate>
    {% csrf_token %}

    {% for field in form %}
    <p>
        <label for="">{{ field.label }}</label>
        {{ field }} <span>{{ field.errors.0 }}</span>
    </p>
    {% endfor %}
    <input type="submit">
</form>
‘‘‘
HTML

 

 

 

以上是关于Django的ModelForm的主要内容,如果未能解决你的问题,请参考以下文章

Django系列

django的文档

Django 大神带你飞系列~走进Django

Django:启动django

django的单元测试怎么用

django-admin 和django-admin.py的区别