Представления на основе класса Django: переопределить имя формы

Я новичок в Джанго. Я пытаюсь построить представление на основе класса, чтобы создать объект.

Имя формы по умолчанию в шаблоне — form, и я хочу изменить его на "ajoutersource", но не могу понять, как это сделать.

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 %}

person Pyrotecnix    schedule 02.11.2015    source источник


Ответы (3)


Переопределить 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
person Sebastian Wozny    schedule 02.11.2015

вы можете сделать это просто следующим методом

Метод 1 (образцовая форма)

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

Метод 2 (простая форма)

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

Метод 1 рекомендуется (Примечание. Это синтаксис Python 3.6+, измените вызов super() на Python 2.0+)

person Nishant Singh    schedule 20.04.2019

Переопределите get_context_data, context['form'] из SomeForm и измените на form_1, вы можете использовать в шаблоне как 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
person Baxromov    schedule 30.07.2021