How to work with time picker widget in Django template?

Amit Pal picture Amit Pal · Aug 14, 2012 · Viewed 11.4k times · Source

I am working on a Django based Application, and i stuck in some place where i want to save a time given by the user and the no of days (Monday-Sunday) in my database.

user will choose a time from Time picker widget or any other way, but it return into the 07 : 30 format.

User will also choose day's from any picker or any other way (user can select multiple days), and it will save into the database.

I tried with the Django-Model field by putting :

timestamp = Models.DatetimeField()

and pass in Django-template using the Django model form, but it shows a text field (which doesn't make any sense).

If, Anyhow it would be possible to get the time in 13:45 format and mon,tue,wed format, then i can also save it into CharField() in database.

I am not able to figure out the solution of above two situation. What are the best option to do it?

Should it be possible with the Java script? (but i am not professional in java script)

Answer

Kapura picture Kapura · Aug 14, 2012

To use the widget, you should indicate in the form class for your model what the widget is:

from django import forms

class MyModelForm(forms.ModelForm):
    timestamp = forms.DateField(widget=forms.DateInput(attrs={'class':'timepicker'}))

If you're using the timestamp property in the model, it operates like a basic python datetime class, with many of the same attributes you would find there. If the format of the timestamp is what's bothering you, you might look at filters that django has for displaying time and datetime fields: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

I'm not certain why you would need to save the timesstamp in a specific format; django's datetime field is pretty robust and easy to work with.