码迷,mamicode.com
首页 > 其他好文 > 详细

Django的ModelForm

时间:2018-06-10 00:31:29      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:max   price   组件   red   UI   ken   closed   用法   let   

这个组件的功能就是把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

标签:max   price   组件   red   UI   ken   closed   用法   let   

原文地址:https://www.cnblogs.com/zgf-666/p/9161666.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!