gpt4 book ai didi

Django - CreateView - 如何声明变量并在模板中使用它

转载 作者:行者123 更新时间:2023-12-04 10:10:27 27 4
gpt4 key购买 nike

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

网址.py:

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

View .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

最佳答案

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

关于Django - CreateView - 如何声明变量并在模板中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9552337/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com