How to work with time picker widget in Django template?

12,777

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.

Share:
12,777
Amit Pal
Author by

Amit Pal

A graduate from IIT(BHU)-Varanasi, India

Updated on June 29, 2022

Comments

  • Amit Pal
    Amit Pal almost 2 years

    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)

  • Amit Pal
    Amit Pal over 11 years
    I tried with your given code, but it shows an text box. What i want that if user don't know the format then how he will enter the time. in database?
  • Hafiz
    Hafiz over 11 years
    @AmitPal Hey Amit, don't forget to add this js code in your template: ` jQuery(document).ready(function(){ jQuery('.timepicker').datepicker(); });`
  • Hafiz
    Hafiz over 11 years
    @AmitPal obviously you will need to import that jquery widget jquery file too