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. ubuntu系统:插入优盘read-only file system

    http://sharadchhetri.com/2013/12/19/how-to-fix-read-only-usb-pen-drive-in-ubuntu/ To fix USB pen dri ...

  2. maven的下载

    1.maven的下载地址:http://maven.apache.org/download.cgi.下载3.3.9版本(在选择下载的版本是要与JDK契合). 2.下载之后,解压的文件放的位置尽量不要有 ...

  3. Halcon的二维码解码步骤和解码技巧

    一.二维码简介 1 . 类型多样,常见的有QR Code二维码. Data Matrix二维码等. 2.高密度编码,信息容量大. 3.容错能力强,具有纠错功能:二维码因穿孔.污损等引起局部损坏时,照样 ...

  4. 讲讲我在Windows10(uwp)开发中遇到的一些坑.

    7月29日发布的Windows10正式版,当天安装好以后,在网络不太好的情况下,经过多次尝试终于装上了Visual Studio 2015和Windows 10 10240的SDK.这两周一直在开发U ...

  5. b3_trcd_EDCD_new

    # -*- coding:utf-8 -*- import re year="17A" ss='./data/' filename = ss+'EDCD%s.txt'%year ' ...

  6. 让tableView的某行移动到tableView的某位置

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:lineNumber inSection:0]; [lrcTableView selectR ...

  7. Ajax请求php返回json对象数据中包含有数字索引和字符串索引,在for in循环中取出数据的顺序问题

    //php中的数组数据格式 Array ( [all] => Array ( [title] => ALL [room_promotion_id] => all ) [best_av ...

  8. [leetcode] 18. Length of Last Word

    这个题目很简单,给一个字符串,然后返回最后一个单词的长度就行.题目如下: Given a string s consists of upper/lower-case alphabets and emp ...

  9. memcached分布式缓存系统

    在数据驱动的Web开发中,经常要重复从数据库中取出相同的数据,这种重复极大的增加了数据库负载.缓存是解决这个问题的好办法.但是ASP.NET中的虽然已经可以实现对页面局部进行缓存,但还是不够灵活.此时 ...

  10. Elasticsearch 相关 api 操作

    A. es 操作 1. 检查 es 集群健康状态 2. 获取集群中的节点列表 3. 创建索引 4. 获取索引 5. 索引文档 6. 查询文档 7. 删除索引 8. 更新文档 9. 删除文档 10. 批 ...