7

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

网址.py:

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

视图.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
4

2 回答 2

16

覆盖 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 文档中有关此的更多信息。

于 2012-03-04T04:51:17.263 回答
0

在模板中你可以使用{{ 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
于 2021-07-30T09:08:15.693 回答