Saturday, October 25, 2008

datepicker without admin

Django's admin interface is one of the really nice things about django because of it's functionality and useful tools. Nearly all of the reviews I have read about django have mentioned a good thing or two about the admin interface. There is however sometimes a need to go beyond or implement a lesser version of admin interface. This is where the adventure of living outside the realm of comfort for me begins ...

I have been trying to live outside the comfort of the admin interface for django and have found other niceties outside of the admin interface namely generic views, forms and others. I have been using these tools to build a web inventory cum sales application for one of our clients and happy to say it has been fairly successful.

Generic views are really powerful and really helps to shave off development time. There are however withdrawal symptoms my code is feeling to the admin interface. I have reimplemented some of the css niceties and javascript in my code. One of the one I am looking for is to re implement the cool datepicker admin has every time it encounters a DateTime or a Date Field.

I have tried a few things towards this goal:

1. Included all the javascript from the admin interface for my page. This just failed silently and my text box looked just the same.
2. Passing the model.DateTime a widget argument in which I call the widgets from django.contrib.admin.widgets. This resulted in a unexpected keyword error.

It would be nice if the django admin team can do a small writeup or a break down on how the admin interface was implemented. This would be really nice as there are some really good stuff in there which can also be useful in it's bits and pieces.

4 comments:

Dougal said...

Shouldn't be too hard....

Having a quick look at the code you need to add the following JS to the page;

ADMIN_ROOT/js/admin/RelatedObjectLookups.js
ADMIN_ROOT/js/calendar.js
ADMIN_ROOT/js/admin/DateTimeShortcuts.js

When you add DateTimeShortcuts.js it initilizes itself. It looks for input elements with classname of vTimeField or vDateField and stores them.

Then look at the href of the <a> surrounding the calendar icon;

javascript:DateTimeShortcuts.openCalendar(0)

The number there relates to the number of the input field. So if you only ever have one on your page it will be 0, the second one will be 1 etc.

I think thats all you need but I've not tested it ;) Let me know if it works

evenrik said...

I use something like this (after adding in the JS) to create a form with a date field that works like the admin:

from django import forms
from django.contrib.admin import widgets
class FooForm(forms.Form):
bar = forms.DateField(widget=widgets.AdminDateWidget)

lowks said...

Found my way to do it too and still using the convenient 'form.as_p' function. Will blog about it later here when I finish up with this app.

OliWarner said...

Did you ever write a follow-up post?