Friday, September 17, 2010

Using the django-admin time and date widgets in your own django app: too hard, use jQuery

The django doco encourages you to use the django admin widgets (such as the time and date picker) in your own apps. Unfortunately actually doing this turns out to be more work than using external widgets like the excellent jQuery-ui.

jQuery comes with good tutorials and doco. jQuery-ui, which builds on jQuery, has a great array of helpful widgets. If, like me, you just want a date picker widget, it is super easy.

You'll want to add something like the following to your template (in your base template if it will be used on every page):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
  jQuery(function()
    {
      jQuery('.vDateField').datepicker({ 
          dateFormat: 'yy-mm-dd',
          constrainInput: 'true', 
          maxDate: ' 1m',
          minDate: '0d' })
    });
</script>

To make it look pretty jQuery has you covered, with ThemeRoller. Pick a style you like, customise it if you need to, and download your new CSS. Drop that in your template too.

No comments: