Domanda

When defining a FormView derived class:

class PrefsView(FormView):
    template_name = "prefs.html"
    form_class = MyForm         # What's wrong with this?
    def get(self,request):
        context = self.get_context_data()
        context['pagetitle'] = 'My special Title'
        context['form'] = MyForm    # Why Do I have to write this?
        return render(self.request,self.template_name,context)

I expected the line context['form'] = MyForm was not needed, since form_class is defined, but without it {{ form }} is not passed to template.
What I'm doing wrong?

È stato utile?

Soluzione

In the context, form should be the instantiated form, not the form class. Defining the form_class is completely separate from including the instantiated form in the context data.

For the example you've given, I think you'd be better to override get_context_data instead of get.

def get_context_data(self, **kwargs):
    context = super(PrefsView, self).get_context_data(**kwargs)
    context['pagetitle'] = 'My special Title'
    return context

Altri suggerimenti

override the get_context_data, context['form'] take from SomeForm, and chage to form_1, you can use in template as form_1

class Something(generic.CreateView):
        template_name = 'app/example.html'
        form_class = forms.SomeForm
        model = models.SomeModel
    
        def get_context_data(self, **kwargs):
            context = super(Something, self).get_context_data(**kwargs)
            context["form_1"] = context["form"]
            context["form_2"] = forms.SomeForm2(**self.get_form_kwargs())
            return context
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top