我在Stackoverflow上查看了其他类似的问题,但那些情况不适用于我。
我有一个表单,其中包含一个“队列”字段,这是一个必填字段。这个表单在多个地方使用,在其中一个实例中,我不想向用户显示“队列”字段。因此,我只需在模板上不呈现它即可。但是因为这是一个必填字段,所以表单无法提交。如何在同时隐藏它不让用户看到的同时预先填充此字段?
我不能更改模型或表单的保存方法,因为该表单也在其他地方使用。
forms.py
我有一个表单,其中包含一个“队列”字段,这是一个必填字段。这个表单在多个地方使用,在其中一个实例中,我不想向用户显示“队列”字段。因此,我只需在模板上不呈现它即可。但是因为这是一个必填字段,所以表单无法提交。如何在同时隐藏它不让用户看到的同时预先填充此字段?
我不能更改模型或表单的保存方法,因为该表单也在其他地方使用。
forms.py
class PublicTicketForm(CustomFieldMixin, forms.Form):
queue = forms.ChoiceField(
widget=forms.Select(attrs={'class': 'form-control'}),
label=_('Queue'),
required=True,
choices=()
)
views.py:
def no_queue(request):
if request.method == 'POST':
form = PublicTicketForm(request.POST, request.FILES)
form['queue'] = 9 # Tried to assign queue value to field, did not work
if form.is_valid():
if text_is_spam(form.cleaned_data['body'], request):
# This submission is spam. Let's not save it.
return render(request, template_name='helpdesk/public_spam.html')
else:
form.save()
else:
form = PublicTicketForm(initial={'queue': 9}) # tried this one too, did not work either
return render(request, 'helpdesk/no_queue.html', {'form': form})