newforms是django新的对表单处理功能,查看官方文档:
http://www.djangoproject.com/documentation/newforms/最近也在看newsform的文章,总结了两种使用的方法,如下所示:
一、根据model自动生成newsformmodel:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--># Create your models here.
class ResType(models.Model):
typename = models.CharField('typename',maxlength=20)
class Admin: pass
def __str__(self):
return self.typename
class Resource(models.Model):
title = models.CharField('标题',maxlength=200)
content = models.TextField('内容',null=True, blank=True)
resdate = models.DateTimeField('发布日期',default=DEFAULT_DATE, blank=True)
restype = models.ForeignKey(ResType)
class Admin:
list_display = ('title',)
def __str__(self):
return self.title
view:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->from django import newforms as forms
def public(request, id=None):
entry = None
if id is None:
EntryForm = forms.models.form_for_model(Resource)
else:
entry = Resource.objects.get(id=id)
EntryForm = forms.models.form_for_instance(entry)
#EntryForm.fields['detail'].widget = TinyMCE()
if request.method == 'POST':
form = EntryForm(request.POST)
if form.is_valid():
entry = form.save(commit=False)
entry.save()
return HttpResponseRedirect("/")
else:
form = EntryForm()
t = loader.get_template('public.html')
c = Context({'form': form,'resource':entry})
return HttpResponse(t.render(c))
template:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->{% load i18n utiltags %}
{% extends "base.html" %}
{% block head%}
{% endblock %}
{% block body %}
<form enctype="multipart/form-data" action="/resource/public/{%ifnotequal resource None %}{{resource.id}}/{%endifnotequal%}" method="post" id="resource_edit">
<div id="message">ddd</div>
<table>
{{ form }}
</table>
<input type="submit" value="OK">
</form>
{% endblock %}
这一种方式主要有如下关键点
1.EntryForm = forms.models.form_for_model(Resource)
生成一个具有Model模型的空的Form,用来显示添加表单
2.EntryForm = forms.models.form_for_instance(entry)
根据一个对象来生成含有该对象数据的Form,用来显示带数据的表单
3.数据保存直接可以通过Post过来的数据创建一Form实例,并调用该实例的save方法
二、自定义Form有时候通过Model自动创建的Form不适合,譬如:Model中的某些属性我不需要显示在页面上,或数据处理方式比较复杂,这个时候你就需要自定义Form.我们先看看代码:
自定义的Form:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->from django.newforms import *
from apps.resource.models import ResType,Tag,Resource
class ResourceForm(Form):
title = CharField(label='标题',required=True)
content = CharField(label='内容',widget=Textarea(attrs={'rows': 10, 'cols': 50}))
resdate = DateField(label='发布日期')
restype = ChoiceField(label='类别',
choices=[(c.id,c.typename) for c in ResType.objects.all()])
def __init__(self, data=None, auto_id='id_%s', prefix=None,initial=None, instance=None):
if instance is not None:
self.instance = instance
new_data = {}
new_data["title"] = instance.title
new_data["content"] = instance.content
new_data["resdate"] = instance.resdate
new_data["restype"] = instance.restype
data = new_data
else:
self.instance = None
super(ResourceForm, self).__init__(data, auto_id, prefix, initial)
def save(self, commit=True):
if self.instance is not None:
instance = self.instance
else:
instance = Resource()
print 'test:'+ self.clean_data["restype"]
instance.title = self.clean_data["title"]
instance.content = self.clean_data["content"]
instance.resdate = self.clean_data["resdate"]
instance.restype = ResType.objects.get(id=self.clean_data["restype"])
if commit:
instance.save()
return instance
该自定义Form类中主要有两部分:
1、重写构造函数,主要是传递数据
2、自定义save方法,用来将Form接收的数据进行处理
View:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->def add_entry(request,id=None):
if id is not None:
instance = Resource.objects.get(id=id)
InstanceForm = ResourceForm(instance=instance)
else:
InstanceForm = ResourceForm()
if request.POST:
form1 = ResourceForm(request.POST)
if form1.is_valid():
form1.save()
return HttpResponseRedirect('/')
t = loader.get_template('add_entry.html')
c = Context({'form': InstanceForm})
return HttpResponse(t.render(c))
其实View部分和第一种方式很相似的,不同的是Form的创建方式。
Template和以前一样。
只写这么多,作为自己学习的一个记录。
参考资料:
http://code.pui.ch/2007/01/07/using-djangos-newforms/http://www.djangoproject.com/documentation/newforms/http://code.djangoproject.com/browser/django/trunk/tests/regressiontests/forms/tests.py
分享到:
相关推荐
django orm 外键操作 练习示例
Django python web
django+vue实现注册登录的示例代码 注册 前台利用vue中的axios进行传值,将获取到的账号密码以form表单的形式发送给后台。 form表单的作用就是采集数据,也就是在前台页面中获取用户输入的值。...
Django注册、登录、注销示例 含源码
Django搭建简易博客示例代码(入门级)
超级验证码supercaptcha 易于使用 django 的验证码字段用法 class MySuperForm ( forms . Form ): captcha = supercaptcha . CaptchaField ( label = u"no robots here" )要求您不需要对形式、中间件、上下文处理器...
django3.4登录示例(python3.4+内附sqlite数据库)
Django示例代码。针对初学者,可以了解Django的开发。
salt-django-example, Django 部署的salt状态树示例 salt-django-example将 Django 应用程序部署到生产服务器的salt状态树。堆栈__Ubuntu: 包名称和堆栈的其他部分只与Ubuntu一起使用为wsgi容器提供反向代理,并为 ...
django的celery和redis简单示例项目
主要介绍了简化Python的Django框架代码的一些示例,实际上文中只是抽取了一些Django中最基本的功能用于简化入门者的上手复杂度,下,需要的朋友可以参考下
Django中每一个模型model都对应于数据库中的一张表,每个模型中的字段都对应于数据库表的列。方便的是,django可以自动生成这些create table, alter table, drop table的操作。其次Django为咱们也提供了后台管理模块...
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so ...
django学习实践简单示例超详细版本源代码
Django添加静态文件有两种方法: 首先setting.py配置文件中添加静态文件的路径: STATICFILES_DIRS = [ os.path.join(BASE_DIR, “statics”),] statices为你所建立的存放静态文件的文件夹名 然后进行引用。 1、...
本源码提供了一个基于Python和Django的百度应用引擎BAE示例应用设计。项目包含2370个文件,其中包括1171个PO文件、826个Python源文件、102个GIF图片、98个HTML文件、68个JavaScript文件、24个CSS样式文件、21个PNG...
本文实例讲述了Django自定义认证方式。分享给大家供大家参考,具体如下: 创建登录应用 首先创建一个新的login app,用来存放认证用到代码 python manage.py startapp login 修改settings.py中的认证项 ...
使用Python Django开发web应用配套的示例代码 python3.6 django2.0。讲义第三页链接https://blog.csdn.net/jxzdsw/article/details/99312523。只是一个简单的blog系统的例子。我是想找到一个分享平台,并不想收取C币...
基于Ubuntu16.04 + Python3 + nginx + mysql + Django 接下来先安装这些必要的环境,这些操作都是在你已经购买了阿里云服务器。并且在本地你已经搭建好了Django博客。现在我们所做的就是把本地的环境在阿里云的...