I looked at other similar questions on Stackoverflow, but those situations do not apply to me.
I have a form with a Queue
field that is a required field. This form is used in multiple places and in one such instance, I don't want the Queue
field to be shown to the user. So, I simply did not render it on the template. But because this a required field, the form won't submit. How do I pre-populate this field while at the same time hiding it from the user?
I cannot make changes to the model or the form's save methods because this form is also used at other places.
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})
The choices
for this form were populated in the views, but because I'm not rendering it in the template, I did not do it.
I was able to do something like this in the template and that worked!
<input type="hidden" name="queue" value="9" />