Search code examples
pythondjangodjango-viewsdjango-context

How to pass argument on custom context_processors.py?


Is it possible to pass some argument from dynamic urls (I have ^c/(?P<username>\w+)/^) to custom context_processors?

views.py (I pass username from url to RequestContext)

def client_profile(request, username):
     # .... some context
     return render_to_response('profile.html', context, 
                                context_instance=RequestContext(request, username))

context_processors.py

def default_profile(request, username):
    client = get_object_or_404(Client, user__username=username)
    #.... some default
    return {
        'client': client,
        #.... some default
    }

I try this, but it was an error when I reload a page

default_profile() missing 1 required positional argument: 'username'

Is any another way to do something like this? Or is it really not possible?

-Thanks.


Solution

  • Context processors are fairly simple, with only 1 argument; HttpRequest

    What you could do, is add something to the session because that would be accessible via the request, but unless it's something system wide or quite generic then you are often better off providing your context variables via your views. Specifically in your example, if you're providing a username in an URL, you are providing a context in the response of that view, so you could simply provide the client at that point.

    Anyway, if you provided something through the session your code might look like;

    def client_profile(request, username):
         # .... some context
         request.session['username'] = username
         return render_to_response(
             'profile.html', context, 
             context_instance=RequestContext(request, username)
         )
    
    def default_profile(request):
        context = {}
        if 'username' in request.session:
            username = request.session['username']
            client = get_object_or_404(Client, user__username=username)
            context.update({
                'client': client,
            })
    
        return context