Answer the question
In order to leave comments, you need to log in
How to define an invisible field in Django?
Good afternoon. How can I add a hidden field with a certain value to the form?
I need to store the title of the product that is currently open in the form.
Found this solution:
title = forms.ModelMultipleChoiceField(
queryset=Room.objects.all())
def __init__(self, *args, room_slug=None, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
if room_slug is not None:
self.fields['title'].queryset = Room.objects.filter(
slug=room_slug
)
title = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, room_slug=None, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
if room_slug is not None:
self.fields['title'].initial = Room.objects.filter(
slug=room_slug
)[0] # 'title': ['<QuerySet [<Room: test room>]>']
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question