【问题标题】:Django Class Based Views : Override form nameDjango 基于类的视图:覆盖表单名称
【发布时间】:2016-02-02 19:40:13
【问题描述】:

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

【问题讨论】:

    标签: python django django-class-based-views django-generic-views


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你可以通过以下方法简单地做到这一点

      方法一(模型形式)

      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+ 的语法,将 super() 调用改为 python 2.0+)

      【讨论】:

        【解决方案3】:

        覆盖get_context_datacontext['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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-10
          • 1970-01-01
          • 2012-02-06
          • 2018-04-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多