1

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')),
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
yossarian
  • 13
  • 3

1 Answers1

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.

Dan Breen
  • 12,626
  • 4
  • 38
  • 49
  • I have considered context_processors, but there is a problem with defining get_blog() function. My blog variable is determined from url retrieved from db, and then checked for user access rights. I don't think I can do this for comment framework urls, as they do not contain blog id. – yossarian Jun 13 '12 at 14:06
  • I edited the answer to show that these processors receive the request variable. That means you could actually get the URL and therefore the blog id for lookup. – Dan Breen Jun 13 '12 at 14:10