Django类视图:覆盖表单名称

3

我是一名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 %}
3个回答

4

覆盖 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

您可以通过以下方法简单地完成它:

方法1(模型表单)

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

方法二(简单形式)

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

推荐使用方法1 (注意:这是Python 3.6+的语法,对于Python 2.0+请更改super()调用)


0

重写 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接