Django - CreateView - How to declare variable and use it in templates

℡╲_俬逩灬. 提交于 2019-12-10 03:57:51

问题


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:

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

回答1:


Override get_context_data and set context_data['place_slug'] = your_slug

Something like this:

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

Some more info on this in the Django docs.



来源:https://stackoverflow.com/questions/9552337/django-createview-how-to-declare-variable-and-use-it-in-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!