How to modify form choices from class?
I have form class:
class Form(forms.ModelForm):
id = forms.ModelChoiceField(queryset=Option.objects.all(), widget=forms.HiddenInput())
category = forms.ModelChoiceField(queryset=Category.objects.all())
class Meta:
model = Option
fields = ('id', 'category')
def choices(self, ext_data):
# something with extdata...
choices = [('1','one')]
category = forms.ModelChoiceField(queryset=choices)
but this:
my_form.choices(something)
is n开发者_运维问答ot working. Why?
I must implement this in class because i have one view and many different forms. Each form have specific choices function.
First, queryset must be a queryset, not a list, since you're using ModelChoiceField
. Second, to reference the category
form field use self.fields['category']
. Your function should thus look something like this:
def choices(self, ext_data):
#I'm not sure what ext_data is, but I suspect it's something to filter the Categories
self.fields['category'].queryset = Category.objects.filter(something=ext_data)
#If ext_data itself is a queryset you can use it directly:
self.fields['category'].queryset = ext_data
For clarification, a queryset is what you get when you use Model.objects.filter(xxx)
or any other filtering action on your model.
Try to use init:
class MessageAdminForm(forms.ModelForm):
def __init__(self, *arg, **kwargs):
super(MessageAdminForm, self).__init__(*args, **kwargs)
# set choices this way
self.fields['field'].choices = [(g.id, g) for g in something]
精彩评论