Skip to content Skip to sidebar Skip to footer

How To Create A Custom Date Time Widget For The Django Admin?

My Problem: I have a model that accepts DateTimeField. The user enters this from the django-admin. But, I cant get a way to get the user's local timezone. So my best shot is forcin

Solution 1:

I think you can create a more generic widget.

First, separate your js, html and media for create a unique widget.

widgets.py

 class DatTimeField(forms.Textarea):
     def render(self, name, attrs = None):
         final_attrs = self.build_attrs(attrs,name=name)
         return "Here you have to return the html of your widget, for example: mark_safe(u'<input type=text %s value=%s class='your_css_class'/>' % (flatatt(final_attrs), value))"

Now in your admin class, try this:

class YourClassAdmin(admin.ModelAdmin): 
    class Media:
        css = {
            "all": ("my_styles.css",)
        }
        js = ("my_code.js",)

    formfield_overrides = {
        models.DateTimeField : {'widget': DatTimeField()},

    }

If you want to customize your widgets, I suggest you to see the TinyMce widget Code. I know it's a way different but this code helped me to develop my own widgets (https://github.com/aljosa/django-tinymce/tree/master/tinymce)

Django docs is also helpful: https://docs.djangoproject.com/en/1.5/ref/forms/widgets/


Post a Comment for "How To Create A Custom Date Time Widget For The Django Admin?"