S
S
s1vemod2021-03-23 09:31:44
Django
s1vemod, 2021-03-23 09:31:44

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
            )


But when the form makes a POST request, this field is not there.

I did this, but I doubt how good this solution is?
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

1 answer(s)
D
Dr. Bacon, 2021-03-23
@s1vemod

Let's start with the fact that for some reason you are passing QuerySet there, and not title

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question