Search code examples
djangotemplatesurlcommentsdjango-context

How to include my base template with custom context in Django comment templates?


I have included Django comments framework in my project, and added custom templates to include my base template instead of the default one.

However, in my base template, there are a few url template tags with dynamic parameters:

{% url galleries blog.pk blog.slug %}

Variable blog is included in the context in my views, but not in the comments framework, which causes No reverse match error when I try to add a comment.

What would be the best way to get variable blog always included in the base template?

Update:

url patterns for blog app:

url(r'^(?P<blog_id>\d+)/(?P<slug>[\-\d\w]+)/galleries/$', 'galleries', name = 'galleries'),
(r'^comments/', include('django.contrib.comments.urls')),

Solution

  • 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.