10.12Django form表单

Posted zhen1996

tags:

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

2018-10-12 15:24:23

From表单参考连接: https://www.cnblogs.com/yuanchenqi/articles/7614921.html

新增了ModelForm的使用,比Form 更省事更简洁!

越努力越幸运!还有30多天完成把luffycity项目完后面还有其他的flask.爬虫什么的,然后就学完啦!

明天周末,把博客再整理一下!!!!!

把自己的博客项目再优化一下!!!233333333!

越努力,越幸运!永远不要高估自己!

 

views.py

from django.shortcuts import render,redirect
from .models import *
from django import forms
from django.forms import widgets as wid
from django.forms import ModelForm


# 让Model转换成form   Meta是配置类
class BookForm(ModelForm):
    class Meta:
        model = Book
        fields = "__all__"
        labels = {
            "title": "书籍名称",
            "price": "价格"
        }
        # 在特定框里面加入 标签
        widgets = {
                "title": wid.TextInput(attrs={"class": "form-control"})
                "price": wid.TextInput(attrs={"class": "form-control"})
                "authors": wid.TextInput(attrs={"class": "form-control"})
            }
        # 配置错误信息
        # error_messages{
        #     "": ""
        # }


# 这些等同于  下面原生的 BookForm(forms.Form) 类


"""原生的BookForm"""
# class BookForm(forms.Form):
#     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())


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


"""用原生form表单做的 """
# def addbook(request):
#     if request.method=="POST":
#         form = BookForm(request.POST)
#         if form.is_valid():
#             print("cleaned_data",form.cleaned_data)
#             title=form.cleaned_data.get("title")
#             price=form.cleaned_data.get("price")
#             date=form.cleaned_data.get("date")
#             publish=form.cleaned_data.get("publish")
#             authors=form.cleaned_data.get("authors") # [1,2]
#             book_obj=Book.objects.create(title=title,price=price,date=date,publish=publish)
#             book_obj.authors.add(*authors)
#             return redirect("/books/")
#     form=BookForm()
#     publish_list=Publish.objects.all()
#     author_list=Author.objects.all()
#     return render(request,"add.html",locals())


"""用ModelForm做的add"""
def addbook(request):
    if request.method=="POST":
        form = BookForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/books/")


"""原生的form"""
# def editbook(request,edit_book_id):
#     if request.method=="POST":
#         title=request.POST.get("title")
#         price=request.POST.get("price")
#         date=request.POST.get("date")
#         publish_id=request.POST.get("publish_id")
#         author_pk_list=request.POST.getlist("author_pk_list") # [1,2]
#
#         Book.objects.filter(pk=edit_book_id).update(title=title,price=price,date=date,publish_id=publish_id)
#         book_obj=Book.objects.filter(pk=edit_book_id).first()
#         book_obj.authors.set(author_pk_list)
#         return redirect("/books/")
#     edit_book=Book.objects.filter(pk=edit_book_id).first()
#     form=BookForm()
#     return render(request,"edit.html",locals())


"""用ModelForm做的edit_books"""
def editbook(request,edit_book_id):
    edit_book = Book.objects.filter(pk=edit_book_id).first()
    if request.method == "POST":
        # 传入个isinstance 对象,让他知道对谁 update
        form = BookForm(request.POST, isinstance=edit_book)
        if form.is_valid():
            form.save()
            return redirect("/books/")
    form = BookForm(isinstance=edit_book)
    return render(request, "edit.html", locals())

add.html和edit_book.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>

<form action="" method="post" novalidate>
     {% csrf_token %}

     {% for field in form %}
        <div>
         {{ field.label }}
         {{ field }}
        </div>
     {% endfor %}

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

 笔记

原生form


forms组件

    ChoiceField(Field)
  
    ModelChoiceField(ChoiceField)
   
    ModelMultipleChoiceField(ModelChoiceField)
   


    1 针对form表单设计form组件
       

modelform

     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")
        authors=models.ManyToManyField("Author")


    class BookForm(forms.Form):
        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())

 

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

11_django中表单的使用流程

Django - forms.Form 无法保存当前用户并且表单有效但未保存

Django高级-Form表单组件应用

Django中的form表单

使用Ajax验证并提交Django表单(django-crispy-forms)

django 模板中的表单字段