day85 ModuleForm

Posted 萌哥

tags:

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

1 forms组件与modelform组件

forms组件:

https://www.cnblogs.com/yuanchenqi/articles/9036474.html
modelForm组件:
https://www.cnblogs.com/yuanchenqi/articles/8034442.html
增删改查----增改涉及form表单

 https://www.kancloud.cn/cyyspring/django/619212

 

Form组件的功能 : 1. 校验字段  ,2. 渲染页面 ,3.显示错误信息.

一 、原生form 的表单增删改查.

1 .modules 文件 

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)
    pub_date =models.DateField()
    publishzd =models.ForeignKey(\'Publish\')
    authors =models.ManyToManyField(\'Author\')

class Publish(models.Model):
    name =models.CharField(max_length=32)

class Author(models.Model):
    name =models.CharField(max_length=32)

  

 2. 

view文件

from django.shortcuts import render,redirect

# Create your views here.
from app01 import models
def books(request):

    book_list =models.Book.objects.all()
    return render(request,\'book_list.html\',{\'book_list\':book_list})


##添加页面
def addbook(request):
    if request.method==\'POST\':
        title =request.POST.get(\'title\')
        price =request.POST.get(\'price\')
        publishzd_id =request.POST.get(\'publish\')
        pub_date =request.POST.get(\'pub_date\')
        authors_pk_list =request.POST.getlist(\'authors\')

        book=models.Book.objects.create(title =title ,price=price ,pub_date = pub_date,publishzd_id=publishzd_id)
        book.authors.set(authors_pk_list)

        models.Book.objects.filter(pk=id).update(title=title, price=price, pub_date=pub_date, publishzd_id=publishzd_id)
        book =models.Book.objects.filter(pk=id).first()
        book.authors.set(authors_pk_list)

        return  redirect(\'/books/\')

    publish_list =models.Publish.objects.all()
    author_list =models.Author.objects.all()
    return render(request,\'addbook.html\',locals())


def changebook(request,id):
    if request.method==\'POST\':
        title =request.POST.get(\'title\')
        price =request.POST.get(\'price\')
        publishzd_id =request.POST.get(\'publish\')
        pub_date =request.POST.get(\'pub_date\')
        authors_pk_list =request.POST.getlist(\'authors\')

        return redirect(\'/books/\')

    publish_list =models.Publish.objects.all()
    author_list =models.Author.objects.all()
    book_edit =models.Book.objects.get(pk =id)

    return render(request,\'changebook.html\',locals())


def deletebook(request,id):
    models.Book.objects.get(pk=id).delete()

    return redirect((\'/books/\'))

url 路由

"""day85 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r\'^$\', views.home, name=\'home\')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r\'^$\', Home.as_view(), name=\'home\')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r\'^blog/\', include(\'blog.urls\'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r\'^admin/\', admin.site.urls),
    url(r\'^books/$\', views.books),
    url(r\'^books/add/$\', views.addbook),
    url(r\'^books/(\\d+)/change/$\', views.changebook),
    url(r\'^books/(\\d+)/delete/$\', views.deletebook),

]
View Code

 

html list页面 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<a href="/books/add/">添加书籍</a>


<ul>
    {% for book in book_list %}
    <li>{{ book.title }}===={{ book.price }}====={{ book.publishzd.name }}
        <a href="/books/{{ book.pk }}/change">编辑</a>
        <a href="/books/{{ book.pk }}/delete">删除</a>
    </li>

    {% endfor %}


</ul>
</body>
</html>
View Code

 

add book 页面

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>addbook</title>
</head>
<body>
<h1>添加页面</h1>
<form action=""method="post">
    {% csrf_token %}
    <p>书籍名称<input type="text" name="title"></p>
    <p>价格<input type="text" name="price"></p>
    <p>出版日期<input type="date" name="pub_date"></p>
    <p>
        <select name="publish" id="">
            {% for publish in publish_list %}
                <option value="{{ publish.pk }}">{{ publish.name }}</option>
            {% endfor %}

        </select>
    </p>
    <p>
        <select name="authors" id="" multiple>
            {% for author in author_list %}
                <option value="{{ author.pk }}">{{ author.name }}</option>
            {% endfor %}

        </select>
    </p>
    <input type="submit">
</form>
</body>
</html>
View Code

 

 

change 页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>changebook</title>
</head>
<body>
<h1>编辑页面</h1>
<form action="" method="post">
    {% csrf_token %}
    <p>书籍名称<input type="text" name="title" value="{{ book_edit.title }}"></p>
    <p>价格<input type="text" name="price" value="{{ book_edit.price }}"></p>
    <p>出版日期<input type="date" name="pub_date" value="{{ book_edit.pub_date|date:\'Y-m-d\' }}"></p>
    <p>
        <select name="publish" id="">
            {% for publish in publish_list %}
                {% if book_edit.publishzd == publish %}
                    <option selected value="{{ publish.pk }}">{{ publish.name }}</option>
                {% else %}
                    <option value="{{ publish.pk }}">{{ publish.name }}</option>
                {% endif %}
            {% endfor %}

        </select>
    </p>
    <p>
        <select name="authors" id="" multiple>
            {% for author in author_list %}
                {% if author in book_edit.authors.all %} }}
                    <option selected value="{{ author.pk }}">{{ author.name }}</option>
                {% else %}
                     <option value="{{ author.pk }}">{{ author.name }}</option>
                {% endif %}
            {% endfor %}
        </select>
    </p>
    <input type="submit" value="提交表单">
</form>
</body>
</html>
View Code

 

 

二、modelform组件功能 

1. 校验字段数据

    forms组件
   (1)校验字段数据  
   
         from django import forms
         class UserForm(forms.Form):
            name = forms.CharField(max_length=32)
            age= forms.IntegerField()
            email = forms.EmailField()
            
            
        form=UserForm({"names":"alex","email":"123@qq.com","age":123})
         
        form=UserForm({"name":"alex"})
        
        form=UserForm({"name":"alex","email":"123@qq.com","age":123,"a":123})

 

配置文件放在view里面 了

from django.shortcuts import render,redirect

# Create your views here.
from app01 import models
def books(request):

    book_list =models.Book.objects.all()
    return render(request,\'book_list.html\',{\'book_list\':book_list})



from django.forms import ModelForm
#将model 和from建立关系


#Modelform 将一个个的model转换成一个form组件
class BookModelForm(ModelForm):
    class Meta:
        model =models.Book
        fields=\'__all__\' #转换所有的模型表( Book表)
        fields=[\'title\',\'price\',\'pub_date\']#也可以指定校验字段


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, \'addbook2.html\', locals())

    form = BookModelForm()
    return render(request, \'addbook2.html\', locals())

def changebook(request,id):
    if request.method==\'POST\':
        book_edit=models.Book.objects.get(pk=id)
        form =BookModelForm(request.POST,instance=book_edit)

        if form.is_valid():
            form.save()#update方法,edit_book.update()
            return redirect(\'/books/\')
        else:
            return render(request,\'addbook2.html\',locals())
    book_edit =models.Book.objects.get(pk =id)
    form = BookModelForm(instance=book_edit)
    return render(request,\'changebook2.html\',locals())
View Code

 

 

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)
    pub_date =models.DateField()
    publishzd =models.ForeignKey(\'Publish\')
    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
View Code

 

 

addbook html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>addbook</title>
</head>
<body>
<h1>添加页面</h1>
<form action=""method="post">
    {% csrf_token %}
   {{ form.as_p}}
    <input type="submit">
</form>
</body>
</html>
View Code

changebook html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>changebook</title>
</head>
<body>
<h1>编辑页面</h1>
<form action="" method="post">
    {% csrf_token %}
   {{ form.as_p }}
    <input type="submit" value="提交表单">
</form>
</body>
</html>
View Code

 

 

 

1. 创建 modelform类

2. 创建 增add 和 改 change

 

 

三、ModelForm的参数

 

#Modelform 将一个个的model转换成一个form组件
class BookModelForm(ModelForm):
    class Meta:
        model =models.Book
        fields=\'__all__\' #转换所有的模型表( Book表)
        # fields=[\'title\',\'price\',\'pub_date\']#也可以指定校验字段

        labels ={\'title\':\'书名\',\'price\':\'价格\'}

        error_messages={
            \'title\':{\'require:\'"书籍名称不能为空"}
              },

        widgets={
            \'pub_date\':wid.TextInput(attrs={\'type\':\'date\'})
        }

    def clean_title(self):
        return self.cleaned_data.get(\'title \')
View Code

 

整理的代码 :

1.  app01/xadmin.py 

 

from Xadmin.service.Xadmin import site,ModelXadmin

from app01.models import *
from django.utils.safestring import mark_safe

class BookConfig(ModelXadmin):
    def edit(self,obj =None,is_header=False):
        if is_header:
            return "操作"
        #反向解析
        return mark_safe("<a herf =\'%s/change\'>编辑</a>"%obj.pk)
        #return mark_safe("<a href=\'%s/change\'>编辑</a>" % obj.pk)

    def check(self,obj=None,is_header=False):
        if is_header:
            return "选择"

        return mark_safe("<input type =\'checkbox\'>")

    def delete(self, obj=None, is_header=False):
        if is_header:
            return "删除"

        return mark_safe(\'a href =\'\'>删除 </a>\')

    def display_authors(self,obj =None,is_header =False):
        if is_header:
            return \'作者\'
        # s =[]
        # # for author in obj.authors.all():
        # #     s.append(author.name)
        #
        # return mark_safe(\',\'.join(s))

    # list_display = [check,\'nid\',\'title\',\'publish\',\'price\',edit,delete]
    # list_display = [check,\'nid\',\'title\',\'publish\',\'price\',display_authors,edit,delete]  #多对多的时候用函数的模式display_authors
    list_display = [check,\'nid\',\'title\',\'publish\',\'price\',\'authors\',edit,delete]


site.register(Book,BookConfig)
site.register(Publish)
site.register(Author)
site.register(AuthorDetail)

  

 2. Xadmin/service/Xadmin.py 

 

from django.conf.urls import url
from django.shortcuts import HttpResponse,render,redirect


class ModelXadmin(object):
    list_display=["__str__",]
    print(\'list_display:\',list_display)

    def __init__(self,model,site):
        self.model =model
        self.site =site

    def list_view(self,request):
        print("self.model:",self.model) #用户访问哪张表,self.model就是谁。
        model_name =self.model._meta.model_name
        data_list = self.model.objects.all()
        print("list_display",self.list_display)##[\'title\',\'price]
        print(\'datalist\',data_list)

        #处理表头
        header_list=[]
        #[check,\'nid\',\'title\',\'publish\',\'price\',edit,delete]
        for field in self.list_display:# model类的字段
            if isinstance(field,str):
                if field ==\'__str__\':
                    print("field",field)
                    val =self.model._meta.model_name.upper()
                    print(\'val\',val)
                else:
                    field_obj =self.model._meta.get_field(field)
                    print(\'11111111111\',field_obj)
                    val =field_obj.verbose_name
                    print(val)
            else:
                val = field(self,is_header=True) #获取表头,传is_header=True
            header_list.append(val)
        #处理表单数据
        new_data_list=[]
        for obj in data_list:# data_list [book_obj,book_obj2...]         data_list = self.model.objects.all()
            print(\'obj:\',obj) #obj Book object 打印的为对象.
            temp =[]
            for field in self.list_display:  #list-display 为在app01下定义的字段. list_display = [check,\'nid\',\'title\',\'publish\',\'price\'
                if isinstance(field,str):
                    from django.db.models.fields.related import ManyToManyField  # 44行到 53行代码为manytomany多对多字段作者显示的。

                    field_obj = self.model._meta.get_field(field)

                    if isinstance(field_obj, ManyToManyField):
                        t = []
                        for i in getattr(obj,field).all():
                            t.append(str(i))
                        val = \',\'.join(t)
                        print(\'manytomany\',val)
                    else:
                        val = getattr(obj,field)  #将属性字符串进行getattr操作 比如:getattr(book_obj,title) 结果为linux ,或者
                else:
                    val =field(self,obj)  #执行app01下 的方法.

                temp.append(val)

            new_data_list.append(temp)

        print(\'data-list:\',data_list)  # data-list: <QuerySet [<Book: linux>, <Book: go>, <Book: python>, <Book: c>]>
        print(\'8888\',new_data_list) #8888 [["<input type =\'checkbox\'>", 1, \'linux\', <Publish: 五道口出版社>, Decimal(\'111.00\'), \'\', "<a herf =\'1/change\'>编辑</a>", \'a href =>删除 </a>\'], ["<input type =\'checkbox\'>", 2, \'go\', <Publish: 上地出版社>, Decimal(\'222.00\'), \'哪吒,苑浩\', "<a herf =\'2/change\'>编辑</a>", \'a href =>删除 </a>\'], ["<input type =\'checkbox\'>", 3, \'python\', <Publish: 五道口出版社>, Decimal(\'333.00\'), \'苑浩,哪吒\', "<a herf =\'3/change\'>编辑</a>", \'a href =>删除 </a>\'], ["<input type =\'checkbox\'>", 4, \'c\', <Publish: 清华出版社>, Decimal(\'444.00\'), \'\', "<a herf =\'4/change\'>编辑</a>", \'a href =>删除 </a>\']]
        return render(request, \'list_view.html\', {"new_data_list": new_data_list,"model_name":model_name,"header_list":header_list})

    def add_view(self,request):
        return render(request,\'add_view.html\')

    def change_view(self,request,id):
        return render(request,\'change_view.html\')

    def delete_view(self,request,id):
        return render(request,\'delete_view.html\')

    def get_urls2(self):
        temp =[]
        temp.append(url(r"^$",self.list_view))
        temp.append(url(\'r^add/$\',self.add_view))
        temp.append(url(\'r^(\\d+)/change/$\',self.add_view))
        temp.append(url(\'r^(\\d+)/delete/$\',self.delete_view))

        return temp

    @property
    def urls2(self):
        print(\'url2\')
        return self.get_urls2(),None,None

class  XadminSite(object):
    def __init__(self,name =\'admin\'):
        self._registry ={}

    def get_urls(self):
        print(self._registry)# {Book:modelAdmin(Book),.....}
        temp = []

        for model, admin_class_obj in self._registry.items():
            #获取当前循环的model的字符串与所在的app字符串
            app_name = model._meta.app_label # \'app01\'
            model_name = model._meta.model_name  #\'book\'

            temp.append(url(r\'^{0}/{1}/\'.format(app_name,model_name),admin_class_obj.urls2),)

            return temp

    @property
    def urls(self):
        print(\'urls\')
        return self.get_urls(),None,None

    def register(self ,model,admin_class =None,**options):
        if not admin_class:
            admin_class =ModelXadmin

        self._registry[model]= admin_class(model,self) #{ BOOK:ModelAdmin(Book),Publish:ModelAdmin(Publish)}

site =XadminSite()

  

 

 

 

 

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

python之路_day85_blog 点赞与评论

背景图片铺满屏幕-------Day85

day06-jsp

IDEA插件系列(85):Day And Night插件——根据日程自动更改配色和主题

DAY85-Django框架(十五) 中间件和CSRF跨站伪装请求

day05_日常SQL练习