【问题标题】:Django - CreateView - How to declare variable and use it in templatesDjango - CreateView - 如何声明变量并在模板中使用它
【发布时间】:2012-03-22 01:55:27
【问题描述】:

如何在 Django 的 Createview 中声明一个变量,以便从它的模板中使用它? 例如,我想在模板中使用 {{ place_slug }}。我从 urls.py 传递它,如下所示:

urls.py:

urlpatterns = patterns('',
    (r'^new/(?P<place_slug>[\w\-\_]+)/?$', PictureCreateView.as_view(), {}, 'upload-new'),
)

views.py:

class PictureCreateView(CreateView):
    model = Picture

    def dispatch(self, *args, **kwargs):
        self.place = get_object_or_404(Place, slug=kwargs['place_slug'])
        return super(PictureCreateView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        more code here

【问题讨论】:

  • 你不应该从你的 urls.py 调用 PictureCreateView.dispatch 吗?
  • as_view 是correct

标签: django django-forms django-templates django-generic-views


【解决方案1】:

覆盖 get_context_data 并设置 context_data['place_slug'] = your_slug

类似这样的:

def get_context_data(self, **kwargs):
    context = super(PictureCreateView, self).get_context_data(**kwargs)
    context['place_slug'] = self.place.slug
    return context

Django docs 中有关此的更多信息。

【讨论】:

    【解决方案2】:

    在模板中你可以使用{{ title }}

    class Something(generic.ListView):
            template_name = 'app/example.html'
            model = models.SomeModel
        
            def get_context_data(self, **kwargs):
                context = super(Something, self).get_context_data(**kwargs)
                context["title"] = "Some title"
                return context
    

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2016-04-15
      • 2019-08-07
      • 2010-10-17
      • 2011-12-06
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 2018-08-04
      相关资源
      最近更新 更多