从Model类中生成的formset,每个表具有一下属性。---> formset 从views post到UI.
for form in formset:
for fiel in form:
fiel.as_hidden
fiel.auto_id
fiel.field
fiel.html_initial_name
fiel.label
fiel.as_text
fiel.css_classes
fiel.form
fiel.html_name
fiel.label_tag
fiel.as_textarea
fiel.data
fiel.help_text
fiel.id_for_label
fiel.name
fiel.as_widget
fiel.errors
fiel.html_initial_id
fiel.is_hidden
fiel.value
view.py 中自定义表单的时候,
required=False用来指定是否可选填。
widget=forms.Textarea,可以指定对应的form显示格式。
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
email = forms.EmailField(required=False,
label='Your e-mail address
)#邮箱为选填项,其他为默认必填项。同时label用于替换verbose_name提示标签信息。
message = forms.CharField(
widget=forms.Textarea
)#CharField默认为input type=text,修改为显示<Textarea>
def clean_message(self):#自定义表单验证.
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationError("Not enough words!")
return message
initial 用来给表单填写默认值。
re_form = ContaceForm(
initial={'subject': 'I love your site!'}
)
html中的容错块,放在form上面即可
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
css渲染:错误列表
<ul class=”errorlist”>
<style type="text/css">
ul.errorlist {
margin: 0;
padding: 0;
}
.errorlist li {
background-color: red;
color: white;
display: block;
font-size: 10px;
margin: 0 0 3px;
padding: 4px 5px;
}
</style>
虽然,自动生成HTML是很方便的,但是在某些时候,你会想覆盖默认的显示。 {{form.as_table}}和其它的方法在开发的时候是一个快捷的方式,form的显示方式也可以在form中被方便地重写。
每一个字段部件(<input type=”text”>, <select>, <textarea>, 或者类似)都可以通过访问{{form.字段名}}进行单独的渲染。
<head> <title>Contact us</title> </head> <body> <h1>Contact us</h1> {% if form.errors %} <p style="color: red;"> Please correct the error{{ form.errors|pluralize }} below. </p> {% endif %} <form action="" method="post"> <div class="field"> {{ form.subject.errors }} <label for="id_subject">Subject:</label> {{ form.subject }} </div> <div class="field"> {{ form.email.errors }} <label for="id_email">Your e-mail address:</label> {{ form.email }} </div> <div class="field"> {{ form.message.errors }} <label for="id_message">Message:</label> {{ form.message }} </div> <input type="submit" value="Submit"> </form> </body> </html>
{{ form.message.errors }} 会在 <ul class="errorlist"> 里面显示,如果字段是合法的,或者form没有被绑定,就显示一个空字符串。 我们还可以把 form.message.errors 当作一个布尔值或者当它是list在上面做迭代, 例如:
<div class="field{% if form.message.errors %} errors{% endif %}">
{% if form.message.errors %} <ul> {% for error in form.message.errors %} <li><strong>{{ error }}</strong></li> {% endfor %} </ul> {% endif %} <label for="id_message">Message:</label> {{ form.message }} </div>
在校验失败的情况下, 这段代码会在包含错误字段的div的class属性中增加一个”errors”,在一个有序列表中显示错误信息。
urls.py 配置文件可以这样写:
旧的:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^hello/$', 'mysite.views.hello'),
(r'^time/$', 'mysite.views.current_datetime'),
(r'^time/plus/(\d{1,2})/$', 'mysite.views.hours_ahead'),
(r'^tag/(\w+)/$', 'weblog.views.tag'),
)
新的:urlpatterns 是可以叠加的。
from django.conf.urls.defaults import *
urlpatterns = patterns('mysite.views',
(r'^hello/$', 'hello'),
(r'^time/$', 'current_datetime'),
(r'^time/plus/(\d{1,2})/$', 'hours_ahead'),
(r'^articles/(\d{4})/(\d{2})/$', views.month_archive),#1
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', views.month_archive),#2
(r'^mydata/birthday/$', views.my_view, {'month': 'jan', 'day': '06'}),#3 访问/
mydata/birthday/等价于访问
/
mydata/2013/06/
(r'^mydata/(?P<month>\w{3})/(?P<day>\d\d)/$', views.my_view),#4
)
urlpatterns += patterns('weblog.views',
(r'^tag/(\w+)/$', 'tag'),
)
url 访问模式
假设访问localhost:8000/articles/2013/06
#1
相当于函数调用-->
month_archive(request, '2013', '06')
#2
相当于函数调用-->
month_archive(request, year='2013', month='06')
有时你会发现你写的视图函数是十分类似的,只有一点点的不同。 比如说,你有两个视图,它们的内容是一致的,除了它们所用的模板不太一样:
# urls.py
from django.conf.urls.defaults import *
from mysite import views
urlpatterns = patterns('',
(r'^foo/$', views.foo_view),
(r'^bar/$', views.bar_view),
)
# views.py
from django.shortcuts import render_to_response
from mysite.models import MyModel
def foo_view(request):
m_list = MyModel.objects.filter(is_new=True)
return render_to_response('template1.html', {'m_list': m_list})
def bar_view(request):
m_list = MyModel.objects.filter(is_new=True)
return render_to_response('template2.html', {'m_list':m_list})
可以如下改进:
# urls.py
from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', (r'^foo/$', views.foobar_view, {'template_name': 'foo.html'}), (r'^bar/$', views.foobar_view, {'template_name': 'bar.html'}), ) # views.py from django.shortcuts import render_to_response from mysite.models import MyModel def foobar_view(request, template_name): m_list = MyModel.objects.filter(is_new=True) return render_to_response(template_name, {'m_list': m_list})
URLconf指定了
template_name
,视图函数会把它当成一个参数。
#3 #4 -- >访问
/mydata/birthday/
, 等价于访问
/mydata/jan/06/
抽取出我们代码中共性的东西是一个很好的编程习惯。 比如,像以下的两个Python函数:
def say_hello(person_name):
print 'Hello, %s' % person_name
def say_goodbye(person_name):
print 'Goodbye, %s' % person_name
我们可以把问候语提取出来变成一个参数:
def greet(person_name, greeting):
print '%s, %s' % (greeting, person_name)
# urls.py
from django.conf.urls.defaults import * from mysite import views urlpatterns = patterns('', (r'^events/$', views.event_list), (r'^blog/entries/$', views.entry_list), ) # views.py from django.shortcuts import render_to_response from mysite.models import Event, BlogEntry def event_list(request): obj_list = Event.objects.all() return render_to_response('mysite/event_list.html', {'event_list': obj_list}) def entry_list(request): obj_list = BlogEntry.objects.all() return render_to_response('mysite/blogentry_list.html', {'entry_list': obj_list})
在重构以后:
# urls.py
from django.conf.urls.defaults import *
from mysite import models, views url
patterns = patterns('',
(r'^events/$', views.object_list, {'model': models.Event}), (r'^blog/entries/$', views.object_list, {'model': models.BlogEntry}),
)
# views.py
from django.shortcuts import render_to_response
def object_list(request,model):
obj_list = model.objects.all()
template_name ='mysite/%s_list.html' % model.__name__.lower()
return render_to_response(template_name, {'object_list':obj_list})
<pre class="cn literal-block" id="cn146" style="padding: 0.3em 0.4em; font-size: 12px; background-color: rgb(224, 255, 184); border-style: solid; border-color: rgb(148, 218, 58); border-width: 1px 0px; overflow: hidden; width: 682px; color: rgb(35, 79, 50); position: relative; line-height: 18px; font-family: Anonymous, Consolas, 'Courier New' !important;">代码块</pre>