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

2

7

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
Rolypoly answered 4/3, 2012 at 4:33 Comment(2)
Shouldn't you be calling PictureCreateView.dispatch from your urls.py?Francesco
as_view is correctAirworthy
A
16

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.

Airworthy answered 4/3, 2012 at 4:51 Comment(0)
U
0

in template you can use {{ 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
Unbutton answered 30/7, 2021 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.