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
. Add an import: from my_app import views
. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
. Add an import: from other_app.views import Home
. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
. Import the include() function: from django.conf.urls import url, include
. 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), ]

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>

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>

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>

二、modelform组件功能 

1. 校验字段数据

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

配置文件放在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())

model 文件

from django.db import models

# Create your models here.
class Book(models.Model):
title =models.CharField(max_length=)
price =models.DecimalField(max_digits=,decimal_places=)
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=)
def __str__(self):
return self.name class Author(models.Model):
name =models.CharField(max_length=)
def __str__(self):
return self.name

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>

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>

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 ')

整理的代码 :

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 Form组件的更多相关文章

  1. Django之Form组件

    Django之Form组件 本节内容 基本使用 form中字段和插件 自定义验证规则 动态加载数据到form中 1. 基本使用 django中的Form组件有以下几个功能: 生成HTML标签 验证用户 ...

  2. Python之路【第二十一篇】:Django之Form组件

    Django之Form组件   Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 小试牛刀 1. ...

  3. 第十一篇:web之Django之Form组件

    Django之Form组件   Django之Form组件 本节内容 基本使用 form中字段和插件 自定义验证规则 动态加载数据到form中 1. 基本使用 django中的Form组件有以下几个功 ...

  4. 小而美的 React Form 组件

    背景 之间在一篇介绍过 Table 组件< React 实现一个漂亮的 Table > 的文章中讲到过,在企业级后台产品中,用的最多且复杂的组件主要包括 Table.Form.Chart, ...

  5. django框架中的form组件的用法

    form组件的使用 先导入: from django.forms import Form from django.forms import fields from django.forms impor ...

  6. Web框架django[Form]组件

    新手上路 Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 小试牛刀 1.创建Form类 # 创 ...

  7. 32.Django form组件

    Form组件 Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 创建Form类时,主要涉及到 [ ...

  8. python Django之Form组件

    python Django之Form组件 Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 小试 ...

  9. django Form组件 上传文件

    上传文件 注意:FORM表单提交文件要有一个参数enctype="multipart/form-data" 普通上传: urls: url(r'^f1/',views.f1), u ...

随机推荐

  1. linux下nginx tomcat集群

    集群系统一般通过两台或多台节点服务器系统通过相应的硬件及软件互连,每个群集节点都是运行其自己进程的独立服务器. 这些进程可以彼此通信,对网络客户机来说就像是形成了一个单一系统,协同起来向用户提供应用程 ...

  2. 类Pinterest Web原型制作分享——花瓣网

    这是一家基于兴趣的社交分享网站,网站为用户提供了一个简单地采集工具,帮助用户将自己喜欢图片重新组织和收藏.网站布局美观合理,内容丰富.此原型模板所用到的组件有按钮栏.菜单栏.搜索框.水平分割线.交互动 ...

  3. msys2 命令行添加镜像地址

    sed -i "1iServer = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/i686" /etc/pacman.d/mi ...

  4. part1:6-Linux文本编辑器vi

    vi编辑器简介: vi是Linux系统的第一个全屏幕交互式编辑器:vim则是vi的升级版得到广大用户青睐. vim有三种工作模式:命令行模式.插入模式.底行模式 命令行模式常用功能键: yy:复制当前 ...

  5. 解决JS中missing ( before function parameters的错误

    在编写javascript中,常出现在function处提示“missing ( before function parameters”的错误,这是怎么回事? 例如: function String. ...

  6. 2018.08.17 洛谷P3135 [USACO16JAN]堡哞(前缀和处理)

    传送门 有趣的前缀和. 数据范围中的n≤200" role="presentation" style="position: relative;"> ...

  7. 2018.07.20 洛谷P4178 Tree(点分治)

    传送门 又一道点分治. 直接维护子树内到根的所有路径长度,然后排序+双指针统计答案. 代码如下: #include<bits/stdc++.h> #define N 40005 using ...

  8. Initialization of bean failed; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'dataSource' of bean class [com.liuyang.jdbc.PersonDao]: No property 'dataSource

    这个错误是说我的启动失败了.这类问题要从配置文件中开始找原因,我用的是spring框架,所以我从application.中找的原因 然后对比路径,对比文件的命名和id,都没有问题,为什么会在启动的时候 ...

  9. HDU 5618 Jam's problem again (cdq分治+BIT 或 树状数组套Treap)

    题意:给n个点,求每一个点的满足 x y z 都小于等于它的其他点的个数. 析:三维的,第一维直接排序就好按下标来,第二维按值来,第三维用数状数组维即可. 代码如下: cdq 分治: #pragma ...

  10. 75. Sort Colors(颜色排序) from LeetCode

      75. Sort Colors   给定一个具有红色,白色或蓝色的n个对象的数组,将它们就地 排序,使相同颜色的对象相邻,颜色顺序为红色,白色和蓝色. 这里,我们将使用整数0,1和2分别表示红色, ...