Django - CreateView - 如何声明变量并在模板中使用它 [英] Django - CreateView - How to declare variable and use it in templates
本文介绍了Django - CreateView - 如何声明变量并在模板中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Django的Createview中声明一个变量,所以我可以从它的模板中使用它?
例如我想在模板中使用{{place_slug}}。我从urls.py传递如下:
How do I declare a variable in Django's Createview, so I can use it from its template? For example I want to use {{ place_slug }} in the template. I pass that from urls.py like below:
urls.py:
urlpatterns = patterns('',
(r'^new/(?P<place_slug>[\w\-\_]+)/?$', PictureCreateView.as_view(), {}, 'upload-new'),
)
views.py: p>
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
推荐答案
覆盖get_context_data并设置context_data ['place_slug'] = your_slug
Override get_context_data and set 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 - 如何声明变量并在模板中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文