我创建了带有选项选项的模型:
SERVICE_CHOICES = (
('Apps', 'Apps'),
('Ask', 'Ask'),
('Auth', 'Auth')
class InputsModelExtended(models.Model):
service = models.CharField(max_length=1000, choices=SERVICE_CHOICES, blank=True)
然后从中创建模型表单:
class InputsModelExtendedForm(ModelForm):
class Meta:
model = InputsModelExtended
widgets = {'service': forms.fields.Select(attrs={'class': 'my_select_boxx'})}
我将此表单传递给views.py:
中的模板def input_form(request):
form = InputsModelExtendedForm
return render(request, 'inputs_forms_css.html', {'form': form})
可以直接从views.py修改“服务”选择集吗? THX。
答案 0 :(得分:0)
不确定。在实例化它时,只需将选择元组作为参数传递给表单类:
# some code left out for brevity
class InputsModelExtendedForm(ModelForm):
class Meta:
model = InputsModelExtended
def __init__(self, *args, **kwargs):
service_choices = kwargs.pop('service_choices')
super(InputsModelExtendedForm, self).__init__(*args, **kwargs)
if service_choices:
self.fields['service'] = forms.ChoiceField(choices=service_choices,
required=False)
# example usage:
def my_view(request):
service_choices = (
('Foo', 'Foo',),
('Bar', 'Bar',),
('Baz', 'Baz',),
)
form = InputsModelExtendedForm(request.POST or None, service_choices=service_choices)
这样您就可以获得在模型上设置的默认值,或者可以从视图中覆盖它。