Answer the question
In order to leave comments, you need to log in
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
class MessageForm(ModelForm):
class Meta:
model = Message
fields = ['group', 'category', 'message_text']
widgets = {
'group': TextInput(attrs={'value': 10}),
}
group
pass 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
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 questionAsk a Question
731 491 924 answers to any question