在我的模型中,我有多种选择,如:
class Choice_Test(models.Model):
TESTS = (('1', 'A'),('2', 'B'),)
option = models.CharField(choices=TESTS, max_length=1)
它的形式:
class Choice_TestCreateForm(forms.ModelForm):
class Meta:
model = Choice_Test
fields=['option']
widgets={'option': forms.Select()}
在模板中:
<label id="options">Options</label>
{{ form_options.option }}
如何从选择输出中删除“A”值?
我已经尝试this,但它对我不起作用。
修改:添加视图代码段
if choices_exist:
choice_form = Choice_TestCreateForm(new_choices=(('1','Z'),),
instance=choice_instance)
choice_form.initial['random_value'] = '99'
else:
choice_form = Choice_TestCreateForm(new_choices=(('1','Z'),))
答案 0 :(得分:0)
我建议您对视图中的选项应用更改,然后将其传递给Choice_TestCreateForm
。您还可以将逻辑移动到模型/ services.py
并在视图中调用此新实现的函数。
forms.py
:
class Choice_TestCreateForm(forms.ModelForm):
class Meta:
model = Choice_Test
fields = ['option']
widgets = {'option': forms.Select()}
def __init__(self, *args, **kwargs):
new_choices = kwargs.pop('new_choices')
super().__init__(*args, **kwargs)
self.fields['option'].choices = new_choices
views.py
:
class NewCreateView(CreateView):
model = Choice_Test
form_class = Choice_TestCreateForm
def get_form_kwargs(self):
form_kwargs = super().get_form_kwargs()
form_kwargs['new_choices'] = (('1', 'A'),)
return form_kwargs
<强>更新强>
基于功能的视图:
def func_view(request):
form = Choice_TestCreateForm(new_choices=(('1', 'Y'),))
return render(request, template_name='template.html', context={'form': form})