K
K
Konstantin Gorodetsky2017-03-28 15:26:02
Django
Konstantin Gorodetsky, 2017-03-28 15:26:02

How to pass value from view to form field?

Hello!
There is the following representation:

class MessageView(CreateView):
    model = Message
    form_class = MessageForm
    template_name = 'mssgs/message_form.html'
    success_url = 'messages'

    def get_context_data(self, **kwargs):
        group_id = self.kwargs['group']
        context = super(MessageView, self).get_context_data(**kwargs)
        context['group'] = Group.objects.get(pk=group_id)

        return context

..and, accordingly, the form:
class MessageForm(ModelForm):

    class Meta:
        model = Message
        fields = ['group', 'category', 'message_text']
        widgets = {
            'group': TextInput(attrs={'value': 10}),
        }

How to grouppass the context value from the view to the form field? Thank you! context['group']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-03-28
@gorodetskiykp

class MessageView(CreateView):
    model = Message
    form_class = MessageForm
    template_name = 'mssgs/message_form.html'
    success_url = 'messages'

    def get_initial(self):
        initial = super(MessageView, self).get_initial()
        group_id = self.kwargs['group']
        initial['group'] = Group.objects.get(pk=group_id)
        return initial

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question