Задать вопрос

Тел: +7 965 3737 888






<p>This snippet defines a Widget that is very similar to the <strong>SelectDateWidget</strong> located in django.forms.extras.widgets. The main difference however is that it works with Times instead of Dates.</p>
<p>The SelectTimeWidget supports both 24-hr and 12-hr formats, and flexible time increments for hours, minutes and seconds. Sample usage is illustrated below:</p>
# 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))

Вопрос полезен? Да0/Нет0

Ответы (3):

Ответ полезен? Да0/Нет0

Ran into the same issue as Skrubly, I indented lines 106/107 one over to make it work.

Ответ полезен? Да0/Нет0

Thanks for this widget! I'm using it in conjunction with your SplitSelectDateTimeWidget.

I did notice a bug - I am using 24 hour time and my initial values are for 00:00:00, but it kept rendering as 12:00:00. It seems that on line 106 it will change hour_val to 12 regardless of whether you are using the 12 hour clock. I changed it from:

elif hour_val == 0:


elif self.twelve_hr and hour_val == 0:

and that seems to have solved my problem.

I've been learning django for about two months - this snippet has been a great help!

Ответ полезен? Да0/Нет0

I am personally using the code found on Github; there are other forks out there too, just search Google for "SelectDateWidget Django".

Being relatively new to Django, it took me a few to figure out how to get this applied to my model and working right in the admin. For those of you that are in the same boat, here's how I got it working:

Put the widget on your system (I put mine in a widgets folder because I had other widget files) and then create (or add to) forms.py:

from django import forms
from dee.widgets.select_time_widget import * # See __all__.
from app.models import Foo

class FooForm(forms.ModelForm):

class Meta:
    model = Foo

time = forms.TimeField(widget=SelectTimeWidget(twelve_hr=True, use_seconds=False, required=False), required=False, label=u'Time')

And in my admin.py:

from django.contrib import admin
from django.db import models
from app.forms import FooForm
from app.models import Foo

class FooAdmin(admin.ModelAdmin):
    form = FooForm
    # ...

admin.site.register(Foo, FooAdmin)

If you have any inlines, don't forget to add form = GameForm to those also.

I hope that helps someone. :)

BTW, it would be cool if this snippet had an option to change the default a.m./p.m. value (i.e. show p.m. by default would be nice).