python3.4 + Django1.7.7 表单的一些问题
上面是没有调用cleaned_data的提交结果,可见模版直接把form里面的整个标签都接收过来了
下面是调用cleaned_data 的结果
django 的表单,提交上来之后是这样的:
#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 < 1:#单词个数
raise forms.ValidationError("your word is too short!")
return message
比如下面这句:
email = forms.EmailField(required=False,label='Email')#非必要字段
其实可以作为非必要字段,required=False
由于调用form.cleaned_data#只有各个字段都符合要求时才有对应的cleaned_data,之前好像必须得:
if form.is_valid():#说明各个字段的输入值都符合要求
所以上述字段required=False,在测试东西或者自己写东西,等安全性不高的场合就比较必要了
#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.core.urlresolvers import reverse
from django.shortcuts import redirect #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 show_readme(request):
if request.method == 'POST':#提交请求时才会访问这一段,首次访问页面时不会执行
form = ContactForm(request.POST) print (form['subject'])
print (form['email'])
print (form['message'])
print ("show ----------------") #“首次访问”和“提交的信息不符合要求”时被调用
return render_to_response('show.html', {'form': form}) 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 render_to_response('contact_author.html', {'form': form})
#return redirect(reverse('','show_readme.html'))
#return HttpResponseRedirect('/thanks/')
return render_to_response('show_readme.html', {'form': cd})
#此处逻辑应该是先生成新的预览页面,再保存为txt #return response else:#首次访问该url时没有post任何表单
form = ContactForm()#第一次生成的form里面内容的格式
print (form)
print (form.is_valid()) #“首次访问”和“提交的信息不符合要求”时被调用
return render_to_response('contact_author.html', {'form': form})
#return render_to_response('show.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
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 ind
#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 response#HttpResponse(data, content_type="text/plain")
提交给模版的html:
<html>
<style type="text/css"> .field{
background-color:#BCD8F5;
}
</style>
<head>
<title>show readme</title>
</head>
<body> <!<div class="field"> {{ form.subject }}
{{ form.email }}
{{ form.message }} <!</div> </body>
</html>
Django本身内建有一些app,例如注释系统和自动管理界面。
app的一个关键点是它们是很容易移植到其他project和被多个project复用。
对于如何架构Django代码并没有快速成套的规则。
如果你只是建造一个简单的Web站点,那么可能你只需要一个app就可以了;
但如果是一个包含许多不相关的模块的复杂的网站,
例如电子商务和社区之类的站点,那么你可能需要把这些模块划分成不同的app,以便以后复用。
数据库模型有有效性验证
C:\Python27\Lib\site-packages\Django-1.7.1-py2.7.egg\django\bin\mysite>python manage.py sqlall books
CommandError: App 'books' has migrations. Only the sqlmigrate and sqlflush commands can be used when an app has migrations.
此时需要输入如下部分即可
C:\Python27\Lib\site-packages\Django-1.7.1-py2.7.egg\django\bin\mysite>python manage.py makemigrations
C:\Python27\Lib\site-packages\Django-1.7.1-py2.7.egg\django\bin\mysite>python manage.py migrate
若上述问题依旧:
Since there is still a bit of backwards compatibility with django 1.6 and below you can still use the sql commands from django-admin. However, you have to delete the migrations folder first.
To get the create statements you need to remove the migrations folder
直接删除books app下面的migrations文件夹
python3.4 + Django1.7.7 表单的一些问题的更多相关文章
- Python3.4 + Django1.7.7 搭建简单的表单并提交
后面还有一个问题,是我把txt生成了,但是网页没有返回我还不知道,现在怎么直接返回txt并且展示出来txt 的内容,希望大牛不吝赐教 首先有一个问题 django1.7之前,这样用: HttpResp ...
- python3.7爬虫:使用Selenium带Cookie登录并且模拟进行表单上传文件
原文转载自「刘悦的技术博客」https://v3u.cn/a_id_142 前文再续,书接上一回,之前一篇文章我们尝试用百度api智能识别在线验证码进行模拟登录:Python3.7爬虫:实时api(百 ...
- 结合API Gateway和Lambda实现登录时的重定向和表单提交请求(Python3实现)
1. 创建Lambda函数,代码如下: from urllib import parse def lambda_handler(event, context): body = event['body' ...
- python3之Django表单(一)
1.HTML中的表单 在HTML种,表单是在<form>...</form>种的元素,它允许用户输入文本,选择选项,操作对象等,然后发送这些数据到服务器 表单元素允许用户在表单 ...
- 循序渐进Python3(十三) --0-- django之form表单
django为我们提供了form表单验证功能,下面来学习一下: 武sir博客:http://www.cnblogs.com/wupeiqi/articles/5246483.html 创建了djan ...
- 【Python3爬虫】当爬虫碰到表单提交,有点意思
一.写在前面 我写爬虫已经写了一段时间了,对于那些使用GET请求或者POST请求的网页,爬取的时候都还算得心应手.不过最近遇到了一个有趣的网站,虽然爬取的难度不大,不过因为表单提交的存在,所以一开始还 ...
- Django之路:QuerySet API,后台和表单
一.Django QuerySet API Django模型中我们学习了一些基本的创建和查询.这里专门讲以下数据库接口相关的接口(QuerySet API),当然你也可以选择暂时跳过这节.如果以后用到 ...
- [转]django自定义表单提交
原文网址:http://www.cnblogs.com/retop/p/4677148.html 注:本人使用的Django1.8.3版本进行测试 除了使用Django内置表单,有时往往我们需要自定义 ...
- Django实现表单验证、CSRF、cookie和session、缓存、数据库多表操作(双下划綫)
通常验证用户输入是否合法的话,是前端js和后端共同验证的,这是因为前端js是可以被禁用的,假如被禁用了,那就没法用js实现验证合法与否了,也就是即使用户输入的不合法,但是也没提示,用户也不知道怎么输入 ...
随机推荐
- android M Launcher之LauncherModel (一)
众所周知 LauncherModel在Launcher中所占的位置,它相当于Launcher的数据中心,Launcher的桌面以及应用程序菜单中所需的数据像 桌面小部件的信息.快捷方式信息.文件信息. ...
- [CSDN_Markdown] Markdown基本语法
简介 本文介绍Markdown的基本使用方法: 使用标题 加粗.斜体 分割线 列表 引用 我写博客一般将可以独立的内容分节,每一节有一个标题,标题的字体应该与正文的字体有点区别.两个相邻节之间使用分割 ...
- 集合框架之Collections静态工具类
Collections类提供了一些列静态的方法,用以更方便地操作集合类 排序机制 一个List可以通过下面的方法进行排序: Collections.sort(list); 如果List包含的是字符串, ...
- Xcode一种涉及到多桌面的调试技巧
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) Mac本身是支持多桌面功能的,以下是本猫OS界面的截图: 可以 ...
- 带你深入理解STL之Stack和Queue
上一篇博客,带你深入理解STL之Deque容器中详细介绍了deque容器的源码实现方式.结合前面介绍的两个容器vector和list,在使用的过程中,我们确实要知道在什么情况下需要选择恰当的容器来满足 ...
- 带你深入理解STL之List容器
上一篇博客中介绍的vector和数组类似,它拥有一段连续的内存空间,并且起始地址不变,很好的支持了随机存取,但由于是连续空间,所以在中间进行插入.删除等操作时都造成了内存块的拷贝和移动,另外在内存空间 ...
- 4.4、Android Studio在命令行运行Gradle
默认情况下,在你的Gradle构建设置中有两种构建类型:一种是为了调试你的应用,debug类型:一种是构建最终的发布版本,release类型.无论你使用哪种模式,你的app必须在安装到设备或虚拟机中之 ...
- 1.QT中播放视频,录音程序的编写
1 通过process的方式播放视频 T22VideoPlayer.pro HEADERS += \ MyWidget.h SOURCES += \ MyWidget.cpp QT += gu ...
- 为你的MacOS App添加开机自启动(Swift)
猴子原创,欢迎转载.转载请注明: 转载自Cocos2Der-CSDN,谢谢! 原文地址: http://blog.csdn.net/cocos2der/article/details/52104828 ...
- UNIX网络编程——SOCKET API和TCP STATE的对应关系_三次握手_四次挥手及TCP延迟确认
在socket系统调用中,如何完成三次握手和四次挥手: SOCK_DGRAM即UDP中的connect操作知识在内核中注册对方机器的IP和PORT信息,并没有建立连接的过程,即没有发包,close也不 ...