如何在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
答案 0 :(得分:15)
覆盖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中的更多相关信息。
答案 1 :(得分: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