后面还有一个问题,是我把txt生成了,但是网页没有返回我还不知道,现在怎么直接返回txt并且展示出来txt 的内容,希望大牛不吝赐教

首先有一个问题

django1.7之前,这样用:

HttpResponse(simplejson.dumps({“status”: ‘200’, “message”:u’登录成功’}), mimetype=’application/json’)

没问题,但是django1,7之后就报错了,查了下问题发现应该这样用:

HttpResponse(simplejson.dumps({“status”: ‘200’, “message”:u’登录成功’}),
content_type
=’application/json’)

html模版:

<html>
<style type="text/css">
{# <ul class="errorlist">。。。</ul> #}
{# ul标签下的class="errorlist"的属性进行渲染 #}{# 标签下的属性 #}
ul.errorlist {
margin: 0;
padding: 0;
}
{# <ul class="errorlist"><li>单词个数低于4个!</li></ul> #}
{# errorlist class下的 li标签内的元素进行渲染 #}{# 属性下一级的标签 #}
.errorlist li {
background-color: red;
color: white;
display: block;
font-size: 10px;
margin: 0 0 3px;
padding: 4px 5px;
}
.field{
background-color:#BCD8F5;
}
</style>
<head>
<title>Contact us</title>
</head>
<body> {% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %} <form action="" method="post">
<div class="field">
This is a brief description of Interim Fix :
{# 自动生成的默认错误信息显示 #}
{# 会被翻译成:<ul class="errorlist"><li>这个字段是必填项。</li></ul> #}
{{ form.subject.errors }}
<label for="id_subject">12</label>
{{ form.subject }}
{# 自定义的错误信息显示 #}
{% if form.subject.errors%}
<label for="id_self_def_error_info" style="color: red;">
*自定义错误信息:主题不能为空
</label>
{% endif %} </div>
<div class="field">
{{ form.email.errors }}
<label for="id_email"> for IBM SPSS Data Collection DDL 7 ("Software").</label>
{{ form.email }}
</div>
<div class="field">
{{ form.message.errors }}
<label for="id_message">页面中自定义的信息:</label>
{{ form.message }}
</div>
<input type="submit" value="提交">
</form>
</body>
</html>

form.py

#coding: gb2312
from django import forms class ContactForm(forms.Form):
subject = forms.CharField(max_length=10,label='subject')#设置最大长度为10
email = forms.EmailField(required=False,label='Email')#非必要字段
message = forms.CharField(widget=forms.Textarea,label='message')#指定form中组件的类型 #自定义校验规则,该方法在校验时被系统自动调用,次序在“字段约束”之后
def clean_message(self):
message = self.cleaned_data['message']#能到此处说明数据符合“字段约束”要求
num_words = len(message.split())
if num_words < 0:#单词个数
raise forms.ValidationError("your word is too short!")
return message

views.py

#coding: gb2312
from django.http import HttpResponse
import datetime,calendar
import time
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from django.template import RequestContext
#from django import form from django.shortcuts import render
from .forms import ContactForm
#from django.shortcuts import render_to_response
#from django_manage_app.forms import ContactForm def current_datetime(request):
now = time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))
html = '<html><body>It is now %s.</body></html>' %now
return HttpResponse(html) def contact_author(request):
if request.method == 'POST':#提交请求时才会访问这一段,首次访问页面时不会执行
form = ContactForm(request.POST)
if form.is_valid():#说明各个字段的输入值都符合要求
cd = form.cleaned_data#只有各个字段都符合要求时才有对应的cleaned_data
#print (form.cleaned_data())
print (cd['subject'])
print (cd['email'])
print (cd['message'])
return HttpResponseRedirect('/thanks/')
else:#有部分字段不符合要求,会有error相关信息给加到form中去,需要覆盖掉
#print (form)
print ('The data does not meet the requirements')
print (form['subject'].errors)
print (form['email'].errors)
print (form['message'].errors)
else:#首次访问该url时没有post任何表单
form = ContactForm()#第一次生成的form里面内容的格式
print (form)
print (form.is_valid()) #“首次访问”和“提交的信息不符合要求”时被调用
return render_to_response('contact_author.html', {'form': form}) def thanks(request): return render_to_response('thanks.html') def download_file(request):
#from django.http import HttpResponse
## CSV
#import csv
#response = HttpResponse(mimetype='text/csv')
#response['Content-Disposition'] = 'attachment; filename=my.csv'
#writer = csv.writer(response)
#writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
#writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) # Text file #要是返回txt放开这部分代码 return response
#response = HttpResponse(content_type="text/plain")
#response['Content-Disposition'] = 'attachment; filename=my.txt'
#response.write("aa/n")
#response.write("bb") # PDF file
#http://code.djangoproject.com/svn/django/branches/0.95-bugfixes/docs/outputting_pdf.txt
#from reportlab.pdfgen import canvas #need pip install reportlab
#response = HttpResponse()#)mimetype='application/pdf')
#response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
#p = canvas.Canvas(response)
#p.drawString(100, 100, "Hello world.")
#p.showPage()
#p.save()
#response = HttpResponse()
fout=open("mysite//test.txt","wt")
str = "hello world"
fout.write(str)
fout.close()
#response['Content-Disposition'] = 'attachment; filename=test.txt'
data = open("mysite//test.txt", "rb").read() html = '<html><body>%s</body></html>' %str
return HttpResponse(data, content_type="text/plain")

参考文献:

http://blog.chedushi.com/archives/7538




Python3.4 + Django1.7.7 搭建简单的表单并提交的更多相关文章

  1. Maven web项目(简单的表单提交) 搭建(eclipse)

    我们将会搭建一个,基于Maven管理的,具有简单的表单提交功能的web项目,使用DAO--service--WEB三层结构,服务器使用Tomcat 1 项目基本结构的搭建 左上角File---> ...

  2. PHP简单利用token防止表单重复提交

    <?php /* * PHP简单利用token防止表单重复提交 * 此处理方法纯粹是为了给初学者参考 */ session_start(); function set_token() { $_S ...

  3. 带有两个输入字段和相关标记的简单 HTML 表单:

    带有两个输入字段和相关标记的简单 HTML 表单: 意思就是说Male 和id="male"绑定在一起. <html> <body>   <p> ...

  4. PHP简单利用token防止表单重复提交(转)

    <?php/* * PHP简单利用token防止表单重复提交 */function set_token() { $_SESSION['token'] = md5(microtime(true)) ...

  5. 【java学习】Servlet简单的表单程序(一)

    此文用于java学习,在此小记. 在此小Demo中使用到了Servlet,所以有必要了解一下Servlet的相关知识.(Servlet的相关知识摘抄自http://blog.csdn.net/jiuq ...

  6. 用jQuery写的最简单的表单验证

    近几天完成了关于我们项目的最简单的表单验证,是用jQuery写的,由于之前也一直没学过jQuery,所以自己也是一直处于边摸索边学习的阶段,经过这一段时间的学习,通过查资料啥的,也发现了学习jQuer ...

  7. angularjs学习第四天笔记(第一篇:简单的表单验证)

    您好,我是一名后端开发工程师,由于工作需要,现在系统的从0开始学习前端js框架之angular,每天把学习的一些心得分享出来,如果有什么说的不对的地方,请多多指正,多多包涵我这个前端菜鸟,欢迎大家的点 ...

  8. Struts2之Action三种接收参数形式与简单的表单验证

    有了前几篇的基础,相信大家对于Struts2已经有了一个很不错的认识,本篇我将为大家介绍一些关于Action接收参数的三种形式,以及简单的表单验证实现,下面进入正题,首先我们一起先来了解一下最基本的A ...

  9. 简单实用的跨域表单POST提交

    我们这里使用了iframe嵌套form表单POST提交,很简单,却能满足get|post等任何复杂情况的要求:缺点是没有返回值. 针对需要的地方加上一个iframe嵌套并塞入隐藏form表单,然后获取 ...

随机推荐

  1. pdflush进程详解

    一.简介     由于页高速缓存的缓存作用,写操作实际上会被延迟.当页高速缓存中的数据比后台存储的数据更新时,那么该数据就被称做脏数据.在内存中累积起来的脏页最终必须被写回磁盘.在以下两种情况发生时, ...

  2. Android样式(style)和主题(theme)

    样式和主题 样式是指为 View 或窗口指定外观和格式的属性集合.样式可以指定高度.填充.字体颜色.字号.背景色等许多属性. 样式是在与指定布局的 XML 不同的 XML 资源中进行定义. Andro ...

  3. SpriteKit游戏Delve随机生成地牢地图一个Bug的修复

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) Delve是一个很有意思的地牢探险类型的游戏,其中每一关的地图 ...

  4. python 如何优雅地退出子进程

    python 如何优雅地退出子进程 主进程产生子进程,子进程进入永久循环模式.当主进程要求子进程退出时,如何能安全地退出子进程呢? 参考一些代码,我写了这个例子.运行之后,用kill pid试试.pi ...

  5. 嵌入式LINUX环境下视频采集知识

    V4L2是Linux环境下开发视频采集设备驱动程序的一套规范(API),它为驱动程序的编写提供统一的接口,并将所有的视频采集设备的驱动程序都纳入其的管理之中.V4L2不仅给驱动程序编写者带来极大的方便 ...

  6. (NO.00005)iOS实现炸弹人游戏(十一):怪物之火精灵

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 从本篇开始我们一次介绍一下游戏中敌人的制作过程.看过第一篇的小 ...

  7. Android游戏开发之SurfaceView的使用-android学习之旅(五)

    SurfaceView和View的区别 View是在ui主线程中,直接响应用户的操作,以及任务的分发,但是任务比较复杂会出现阻塞. SurfaceView则不会出现这种问题,以为它直接从内存等取得图像 ...

  8. [ExtJS5学习笔记]第四节 欢迎来到extjs5-手把手教你实现你的第一个应用

    本文地址:http://blog.csdn.net/sushengmiyan/article/details/38331347 本文作者:sushengmiyan ------------------ ...

  9. 修改GDAL库支持IRSP6数据

    使用GDAL库发现不能打开IRSP6的数据,不过看GDAL提供的文件格式里面却是支持IRSP6的数据的,具体可以参考网页http://www.gdal.org/frmt_fast.html.下面图1是 ...

  10. linux内核cfs浅析

    linux调度器的一般原理请参阅<linux进程调度浅析>.之前的调度器cfs之前的linux调度器一般使用用户设定的静态优先级,加上对于进程交互性的判断来生成动态优先级,再根据动态优先级 ...