views:

302

answers:

1

I have a model formset on a model with a couple of date fields - which again is a DateTimeField in the model. But when it displays in the template, it is shown as a text field. How can I show it as a drop down box ?

WFormSet = inlineformset_factory(UserProfile, W, can_delete=False,exclude=[<list of fields to be excluded>], extra=3)

This is how I am intializing the modelformset.

How do I override these settings

+3  A: 

The usual way to do this is to override the default field types in your ModelForm definition.

The example below would work if you had a DateField in your model (I note you have a DateTimeField... I'll come back to that in a sec). You're going to be specifying the exact same field type as would normally be specified, but you'll pass a different widget to the form field constructor.

from django.db import models
from dango import forms
from django.forms.extras import SelectDateWidget

class MyModel(models.Model):
    a_date_field = models.DateField()

class MyModelForm(forms.ModelForm):
    a_date_field = forms.DateField(widget=SelectDateWidget())

    class Meta:
        model = MyModel

There isn't, to my knowledge, an equivalent widget provided for the DateTimeField in Django 1.0.x. In this case, you'll want to make a custom widget, perhaps subclassing SelectDateWidget. I note from a quick google on SelectDateTimeWidget that there have been several others who've been making what appear to be the widget you're seeking. I've not used them, so caveat emptor, but something like this SelectDateTimeWidget patch might be a good place to start.


Edit: When using a ModelFormset or InlineModelFormset, you can still achieve this by passing form=MyModelForm to the inlineformet_factory function:

MyModelFormset = inlineformset_factory(MyParentModel, MyModel, form=MyModelForm)

This works because the two model formset factories actually call the regular formset_factory constructor in their own implementations. It's a little hard to figure out because it's not explicitly stated in the docs... rather the Django docs allude to this ability by mentioning in passing that the model formset factories extend the normal formset_factory. Whenever I'm in doubt, I open django/forms/models.py to check out the full signature of the formset factory functions.

Jarret Hardie
Thanks for the reply,However i forgot to mention that I am using inlineformset to initialise the form. I have edited the question also.
crashekar
No worries... I've updated the answer.
Jarret Hardie
Good answer. But... "proscribed" means "forbidden" - I don't think that's what you meant. Perhaps "prescribed" is closer to the meaning you're looking for.
Carl Meyer
HAHAHAHA... now that's a typo almost worth leaving in.
Jarret Hardie