[Django]-Django Class Based Views : Override form name

4👍

Override get_context_data():

class ajoutSource(CreateView):
    model = Source
    template_name = "pmd/ajouterSource.html"
    form_class = AjouterSourceForm
    success_url = reverse_lazy(ListerSources)

    def get_context_data(self, **kwargs):
        context = super(ajoutSource, self).get_context_data(**kwargs)
        context["ajoutersource"]=context["form"]
        return context

1👍

you can do it simply by following method

Method 1 (Model Form)

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['new_name'] = self.get_form()
    return context

Method 2 (Simple Form)

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['new_name'] = context["form"]
    return context

Method 1 is recommended
(Note: This is python 3.6+ syntax, change super() call for python 2.0+)

0👍

Override the get_context_data, context['form'] take from SomeForm, and change 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

Leave a comment