When creating a flatpage, I want the user to select a template from a predefined list. In order to keep the Flatpage
model untouched, I prefer ChoiceField
over ModelChoiceField
(the latter provides the PK of the template, but I need the name for the template_name field):
class NewFlatpageForm(FlatpageForm):
template_name = forms.ChoiceField(choices = [])
def __init__(self, *args, **kwargs):
self.base_fields['template_name'].choices = ProjectTemplate.objects.values_list('path', 'name')
super(NewFlatpageForm, self).__init__(*args, **kwargs)
I override __init__
or Django populates choices at server start and does not update the list then.
I don't have any admin experience, but I did similar things using the fields
attribute when not using admin. However in this case, I got an exception telling fields
is not an attribute of the form. __dict__
showed me there's a base_fields
attribute and using it works. So, why use base_fields here, and why is fields
not present and finally am I doing something hacky?