[Answered ]-How to include my base template with custom context in Django comment templates?

2👍

Create yourself a context processor. These are just functions that return a dict whose items will be available anywhere in your templates. Typically you will create a context_processor.py file in the relevant Django app, then include this in your TEMPLATE_CONTEXT_PROCESSORS setting.

E.g.:

project/myapp/context_processors.py:

def blog(request):
    return {
        'blog': get_blog(),
    }

In your settings:

TEMPLATE_CONTEXT_PROCESSORS = (
    # ... standard django ones here ...
    'project.myapp.context_processors.blog',
)

Now blog will be available in all your templates.

EDIT: I forgot that these context processor methods receive the request as an argument which lets you do more powerful stuff.

EDIT 2: Per your update showing the URL patterns… You could create a piece of middleware that picked off the blog_id from the kwargs and add it to the request object:

class BlogMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
         blog_id = view_kwargs.pop('blog_id', None)
         if blog_id:
             request.blog = Blog.objects.get(id=blog_id)

Now you can access the blog in the templates using either {{ request.blog }} or you could use the context processor still.

Leave a comment