sinθ
sinθ

Reputation: 11493

Django: Views within views

This may seem very basic, but, though I can guess, how do you make a view within a view, or more accurately, a dynamic template within a dynamic template. You see, I have these blocks of html which contain stats on certain things. How would I create a view that returned one of these boxes so another view could insert them into a template block? Is it "ok" to just have a function which returns it, or do I "have to" follow the same functionName(request) thing instead of functionName(info1, info2, info3) like a normal function. This seems like such a common thing that there would be some sort of standard.

Upvotes: 0

Views: 174

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239290

If I understand you, you're basically talking about pre-populating the template context. Basically, you want a common bit of context to be present in a number of views, but you don't want to repeat yourself for each view. Using function-based views, the best way is to simply have generic method that takes care of this:

def add_some_context(context={}):
    context['foo'] = 'bar'
    return context

def view1(self, request):
    context = {
        'something1': 'blah',
    }
    return render_to_response('template1.html', add_some_context(context), context_instance=RequestContext(request))

def view2(self, request):
    context = {
        'something2': 'blah',
    }
    return render_to_response('template2.html', add_some_context(context), context_instance=RequestContext(request))

Both views will have a foo context variable you can use, then. Doing it with class-based views, you can create a mixin class:

class MyViewMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MyViewMixin, self).get_context_data(**kwargs)
        context['foo'] = 'bar'
        return context

class MyView1(MyViewMixin, DetailView):
    ...

class MyView2(MyViewMixin, ListView):
    ...

When it comes time to add this to the actual template, you can have each view's template inherit from a template that implements the foo context variable in some way.

If it's something that should be applied to every view, then a context processor is more appropriate, but if it's just for a handful of views, then these two methods will serve you well.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

This is exactly what custom template tags - in particular inclusion tags - are for.

Upvotes: 2

Related Questions