Django - CreateView - how to declare a variable and use it in templates

How to declare a variable in Django Createview, so I can use it from my template? For example, I want to use {{place_slug}} in a template. I pass this from urls.py as shown 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
+5
source share
1 answer

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

Something like that:

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

More info on this at Django docs .

+12
source

All Articles