Reputation: 1307
I have a ModelForm
class in which I set a couple of the fields as ChoiceField
. For one of my views, I'd like to create a form from my ModelForm
class that pulls from an instance of my model in the database (like so):
form = MyModel(instance=model_instance)
When I do this and then render the form in a template, I've noticed that most of the fields are pre-populated with values pulled from the model instance, which is what I want. However, this isn't the case for two ChoiceField
fields. These render as drop-down select menus with no specific option selected.
What's strange is if I don't define those two fields as ChoiceField
-type in my ModelForm class, they render as normal text input fields in HTML and pre-populate using the database values. But when I define them so they show up as select-option input fields in HTML, nothing is pre-selected. Can I change this so that the values from the database are pre-selected?
EDIT: As requested here is the code for my model and form:
class App(models.Model):
CODES = (
(u'a',u'annual'),
(u'm',u'monthly'),
(u'w',u'weekly')
)
code = models.CharField(max_length=1, choices=CODES)
start_time = models.TimeField(blank=True, null=True)
end_time = models.TimeField(blank=True, null=True)
class AppForm(ModelForm):
CODES = (
(u'',u'Please select code'),
(u'a',u'annual'),
(u'm',u'monthly'),
(u'w',u'weekly')
)
TIMES = (
(u'00:00',u'All Day'),
(u'12:00',u'Noon')
)
start_time = forms.ChoiceField(required=False, choices=TIMES)
end_time = forms.ChoiceField(required=False, choices=TIMES)
code = forms.ChoiceField(choices=CODES, label='Type')
class Meta:
model = App
Interestingly, code
field has the model instance value preselected just fine when rendered as HTML. I wonder if having the choices
argument in the model definition makes the difference here?
UPDATE: I just noticed that if I pull up an App
instance in the python manage.py shell
like so:
a = App.objects.get(id=16)
a.start_time
I get a value like datetime.time(12, 0)
. But in the Django admin, when I'm looking at all of the App
instances, all of them show (None)
under start_time
and end_time
. Why would that be?
Upvotes: 1
Views: 4293
Reputation: 5656
In response to your update : your times strings match default time string HH:MM format. Just like a user would enter them from website manually 12:00. The values get parsed and turned into time at model save (at validating really).
And when you load model - then of course the initial values loaded from object match the field's (models.TimeField) type.
If you replace your TIMES with
(datetime.time(0,0),u'All Day'),
(datetime.time(12,0),u'Noon')
your troubles should be over.
Alan
Upvotes: 1