上面是没有调用cleaned_data的提交结果,可见模版直接把form里面的整个标签都接收过来了

下面是调用cleaned_data 的结果

django 的表单,提交上来之后是这样的:

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

比如下面这句:

email = forms.EmailField(required=False,label='Email')#非必要字段

其实可以作为非必要字段,required=False

由于调用form.cleaned_data#只有各个字段都符合要求时才有对应的cleaned_data,之前好像必须得:

if form.is_valid():#说明各个字段的输入值都符合要求

所以上述字段required=False,在测试东西或者自己写东西,等安全性不高的场合就比较必要了

  1. #coding: gb2312
  2. from django.http import HttpResponse
  3. import datetime,calendar
  4. import time
  5. from django.http import HttpResponse
  6. from django.template import Context
  7. from django.template.loader import get_template
  8. from django.http import HttpResponse, Http404
  9. from django.contrib.auth.models import User
  10. from django.shortcuts import render_to_response
  11. from django.http import HttpResponseRedirect
  12. from django.contrib.auth import logout
  13. from django.template import RequestContext
  14. from django.core.urlresolvers import reverse
  15. from django.shortcuts import redirect
  16.  
  17. #from django import form
  18.  
  19. from django.shortcuts import render
  20. from .forms import ContactForm
  21. #from django.shortcuts import render_to_response
  22. #from django_manage_app.forms import ContactForm
  23.  
  24. def current_datetime(request):
  25. now = time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))
  26. html = '<html><body>It is now %s.</body></html>' %now
  27. return HttpResponse(html)
  28.  
  29. def show_readme(request):
  30. if request.method == 'POST':#提交请求时才会访问这一段,首次访问页面时不会执行
  31. form = ContactForm(request.POST)
  32.  
  33. print (form['subject'])
  34. print (form['email'])
  35. print (form['message'])
  36. print ("show ----------------")
  37.  
  38. #“首次访问”和“提交的信息不符合要求”时被调用
  39. return render_to_response('show.html', {'form': form})
  40.  
  41. def contact_author(request):
  42. if request.method == 'POST':#提交请求时才会访问这一段,首次访问页面时不会执行
  43. form = ContactForm(request.POST)
  44. if form.is_valid():#说明各个字段的输入值都符合要求
  45. cd = form.cleaned_data#只有各个字段都符合要求时才有对应的cleaned_data
  46. #print (form.cleaned_data())
  47.  
  48. print (cd['subject'])
  49. print (cd['email'])
  50. print (cd['message'])
  51. #return render_to_response('contact_author.html', {'form': form})
  52. #return redirect(reverse('','show_readme.html'))
  53. #return HttpResponseRedirect('/thanks/')
  54. return render_to_response('show_readme.html', {'form': cd})
  55. #此处逻辑应该是先生成新的预览页面,再保存为txt
  56.  
  57. #return response
  58.  
  59. else:#首次访问该url时没有post任何表单
  60. form = ContactForm()#第一次生成的form里面内容的格式
  61. print (form)
  62. print (form.is_valid())
  63.  
  64. #“首次访问”和“提交的信息不符合要求”时被调用
  65. return render_to_response('contact_author.html', {'form': form})
  66. #return render_to_response('show.html', {'form': form})
  67.  
  68. def thanks(request):
  69.  
  70. return render_to_response('thanks.html')
  71.  
  72. def download_file(request):
  73. #from django.http import HttpResponse
  74. ## CSV
  75. #import csv
  76. #response = HttpResponse(mimetype='text/csv')
  77. #response['Content-Disposition'] = 'attachment; filename=my.csv'
  78. #writer = csv.writer(response)
  79. #writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
  80. #writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
  81.  
  82. # Text file
  83. response = HttpResponse(content_type='text/plain')
  84. response['Content-Disposition'] = 'attachment; filename=my.txt'
  85. response.write("aa\n")
  86. response.write("bb")
  87.  
  88. # PDF file
  89. #http://code.djangoproject.com/svn/django/branches/0.95-bugfixes/docs/outputting_pdf.txt
  90. #from reportlab.pdfgen import canvas #need pip ind
  91. #response = HttpResponse()#)mimetype='application/pdf')
  92. #response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
  93. #p = canvas.Canvas(response)
  94. #p.drawString(100, 100, "Hello world.")
  95. #p.showPage()
  96. #p.save()
  97.  
  98. #response = HttpResponse()
  99. fout=open("mysite//test.txt","wt")
  100. str = "hello world"
  101. fout.write(str)
  102. fout.close()
  103. #response['Content-Disposition'] = 'attachment; filename=test.txt'
  104. data = open("mysite//test.txt", "rb").read()
  105.  
  106. html = '<html><body>%s</body></html>' %str
  107. return response#HttpResponse(data, content_type="text/plain")

提交给模版的html:

  1. <html>
  2. <style type="text/css">
  3.  
  4. .field{
  5. background-color:#BCD8F5;
  6. }
  7. </style>
  8. <head>
  9. <title>show readme</title>
  10. </head>
  11. <body>
  12.  
  13. <!<div class="field">
  14.  
  15. {{ form.subject }}
  16. {{ form.email }}
  17. {{ form.message }}
  18.  
  19. <!</div>
  20.  
  21. </body>
  22. </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 表单的一些问题的更多相关文章

  1. Python3.4 + Django1.7.7 搭建简单的表单并提交

    后面还有一个问题,是我把txt生成了,但是网页没有返回我还不知道,现在怎么直接返回txt并且展示出来txt 的内容,希望大牛不吝赐教 首先有一个问题 django1.7之前,这样用: HttpResp ...

  2. python3.7爬虫:使用Selenium带Cookie登录并且模拟进行表单上传文件

    原文转载自「刘悦的技术博客」https://v3u.cn/a_id_142 前文再续,书接上一回,之前一篇文章我们尝试用百度api智能识别在线验证码进行模拟登录:Python3.7爬虫:实时api(百 ...

  3. 结合API Gateway和Lambda实现登录时的重定向和表单提交请求(Python3实现)

    1. 创建Lambda函数,代码如下: from urllib import parse def lambda_handler(event, context): body = event['body' ...

  4. python3之Django表单(一)

    1.HTML中的表单 在HTML种,表单是在<form>...</form>种的元素,它允许用户输入文本,选择选项,操作对象等,然后发送这些数据到服务器 表单元素允许用户在表单 ...

  5. 循序渐进Python3(十三) --0-- django之form表单

    django为我们提供了form表单验证功能,下面来学习一下: 武sir博客:http://www.cnblogs.com/wupeiqi/articles/5246483.html  创建了djan ...

  6. 【Python3爬虫】当爬虫碰到表单提交,有点意思

    一.写在前面 我写爬虫已经写了一段时间了,对于那些使用GET请求或者POST请求的网页,爬取的时候都还算得心应手.不过最近遇到了一个有趣的网站,虽然爬取的难度不大,不过因为表单提交的存在,所以一开始还 ...

  7. Django之路:QuerySet API,后台和表单

    一.Django QuerySet API Django模型中我们学习了一些基本的创建和查询.这里专门讲以下数据库接口相关的接口(QuerySet API),当然你也可以选择暂时跳过这节.如果以后用到 ...

  8. [转]django自定义表单提交

    原文网址:http://www.cnblogs.com/retop/p/4677148.html 注:本人使用的Django1.8.3版本进行测试 除了使用Django内置表单,有时往往我们需要自定义 ...

  9. Django实现表单验证、CSRF、cookie和session、缓存、数据库多表操作(双下划綫)

    通常验证用户输入是否合法的话,是前端js和后端共同验证的,这是因为前端js是可以被禁用的,假如被禁用了,那就没法用js实现验证合法与否了,也就是即使用户输入的不合法,但是也没提示,用户也不知道怎么输入 ...

随机推荐

  1. weblogic静默方式创建域

    创建域目录:mkdir -p /home/weblogic/Oracle/Middleware/user_projects/domains/base_domain/ 创建文件: create_doma ...

  2. 转:window与linux互相拷贝文件

    window与linux互相拷贝文件   借助 PSCP 命令可以实现文件的互拷:     1.下载pscp.exe 文件 (我的资源文件中有)   2.如果想在所有目录可以执行,请更改环境变量. w ...

  3. Rstudio-server 重新登录载入session的问题

    Rstudio-server 非常好用,但是免费版的也有一些问题,一个是只能支持在一个客户端的登录,另一个就是每次登录都要导入之前session的问题,对于第二个问题的解决方案,我们可以进入到~/.r ...

  4. Go 语言数组

    Go 语言提供了数组类型的数据结构. 数组是具有相同唯一类型的一组已编号且长度固定的数据项序列,这种类型可以是任意的原始类型例如整形.字符串或者自定义类型. 相对于去声明number0, number ...

  5. 自定义Retrofit转化器Converter

    我们来看一下Retrofit的使用 interface TestConn { //这里的Bitmap就是要处理的类型 @GET("https://ss0.baidu.com/73F1bjeh ...

  6. Apache shiro集群实现 (二) shiro 的INI配置

    Apache shiro集群实现 (一) shiro入门介绍 Apache shiro集群实现 (二) shiro 的INI配置 Apache shiro集群实现 (三)shiro身份认证(Shiro ...

  7. Android Stutio中使用java8的Lambda表达式

    转载请标明出处: http://blog.csdn.net/xmxkf/article/details/51532028 本文出自:[openXu的博客] 目录: 为什么要使用Lambda表达式 让A ...

  8. CentOS升级Svn到最新版

    CentOS升级Svn到最新版(金庆的专栏)CentOS/RHEL yum 安装的 subversion 是 1.6.11 版本,连VisulaSVN服务器时会有"Key usage vio ...

  9. Android Studio基本配置

    主题设置 File→Settings- 添加第三方主题 网址:http://www.ideacolorthemes.org/home/ File→Import Settings- 设置控制台字体大小 ...

  10. Python中使用rrdtool结合Django进行带宽监控

    我们有个网关需要做下带宽监控,能获取这个数据的唯一方法就是登录到管理界面查看.然后咱就写了个模拟登录的爬虫,定时抓取数据用rrdtool存储,最后通过Django来展示.这里就涉及了python的rr ...