未加星标

SelectTimeWidget: A custom Django Widget

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二03 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

I've been meaning to write this blog post for quite some time...

Django Models provide a way to create a definitive source of data for web applications. Written as a python class, a Django Model consists of Fields that (among other things) define a type for your data.

Django's Forms provide a mechanism for generating HTML form elements and validating user input. A sublcass of Django's Form class is the ModelForm which essentially creates a Form based on the Fields in a Model. Form Fields and Model Fields are not the same--though there is a mapping from Model fields to Form fields , however. The Fields in a Form define the validation logic for the data entered into the html form elements generated by the Field.

When Django renders a Form, it chooses an appropriate html form element (such as input, textarea, or select elements) based on the type of Fields in the Form. For example a form to save a URL with an associated title might look something like the following:

from django import forms
class LinkForm(forms.Form):
title = forms.CharField()
url = forms.URLField()

The HTML generated by calling this forms as_table() method might look something like this:

>>> f = LinkForm()
>>> f.as_table()
<tr><th>Title:</th><td><input type="text" name="title" /></td></tr>
<tr><th>Url:</th><td><input type="text" name="url"/></td></tr>

We can change the behaviour of this output HTML by specifying a specific widget for the Form. If for some strange reason we wanted the Title to render in a textarea, we would do the following:

title = forms.CharField(widget=forms.Textarea)

All of this is well-documented in Django's Widget documentation , which has been working well for me 80% of the time.

My big complaint here is that Date and Time information defaults to text input elements. In the past, I've always liked to use select elements for situations when users would need to enter things like dates (perhaps a different select element for Months, Days, and Years) and time (different select elements for Hours, Minutes...

Luckily, (as of version 1.0, I think), Django offers a SelectDateWidget (located in django.forms.extras.widgets ) which accomplishes this very thing. It produces three select elements, and it can be attached to a Form's DateField. This is accomplished like so:

some_date = forms.DateField(widget=SelectDateWidget, initial=datetime.date.today())

That's Awesome! I can even tell the widget to default to "today's" date by passing it an initial parameter containing the value generated by datetime.date.today() . Ok... what about times? Would we ever want to enter Time information as three separate select elements. I do, so I basically altered the SelectDateWidget , creating a SelectTimeWidget , which is available on django snippets . It isn't perfect, but for now, it has accomplished what I've wanted... and its fairly flexible.

# Specify a basic 24-hr time Widget (the default)
t = forms.TimeField(widget=SelectTimeWidget())
# Force minutes and seconds to be displayed in increments of 10
t = forms.TimeField(widget=SelectTimeWidget(minute_step=10, second_step=10))
# Use a 12-hr time format, which will display a 4th select
# element containing a.m. and p.m. options)
t = forms.TimeField(widget=SelectTimeWidget(twelve_hr=True))

However, I often use DateTimeFields in both Models and Forms (which consists of date and time info). All the code I need to represent select elements for such a field exists in both SelectDateWidget and SelectTimeWidget s. The problem? I just have figured out a good (read: proper) way to combine these two Widget classes.

Do I use multiple inheritance here... mixins... ? My experience doing this in python is a bit rusty... (erm, non-existent!) Hopefully the helpful django community will help me out. :)

UPDATE: This discussion is continued in Extending Django's MultiWidget: SplitSelectDateTimeWidget . I found a solution to this problem simply by digging through Django's source code. Huzzah for Open Source!

So if you had a project called mysite and an app called myapp , putting it all together would look something like this:

# in urls.py
urlpatterns += patterns('',
(r'^test/$', 'mysite.myapp.views.test'),
)
# in forms.py
class TestForm(forms.Form):
t = forms.TimeField(widget=SelectTimeWidget(minute_step=15, second_step=30, twelve_hr=True))
# in views.py
def test(request):
from forms import TestForm
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():info = form.cleaned_data
else:
form = TestForm()
return render_to_response('myapp/test.html',
locals(), context_instance=RequestContext(request))

And the test.html Template:

{% extends "base.html" %}
{% block content %}
{% if info %}
<pre>{{ info }}</pre>
{% else %}
<form action="" method="post">
{{ form.as_p }}
<p><input type="submit" value="go"/></p>
</form>
{% endif %}
{% endblock %}

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: DjangoHTML
分页:12
转载请注明
本文标题:SelectTimeWidget: A custom Django Widget
本站链接:http://www.codesec.net/view/479754.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(78)