Search code examples
pythondjangodjango-class-based-viewsdjango-generic-views

Django Class Based Views : Override form name


I'm new in Django. I try to build a class based view in order to create an object.

The default name of the form in the template is form and I want to change it to "ajoutersource" but I can't figure how.

views.py

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

ajouterSource.html

{% for field in ajoutersource %} 
    <div class="row"> 
        {% if field.errors %}
            <div class="error">{{ field.errors }}</div> 
        {% endif %}
        <div class="label">{{ field.label }}</div> 
        <div class="field">{{ field }}</div>
    </div> 
{% endfor %}

Solution

  • 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