1

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.

A. Fynn
  • 39
  • 6
  • What are you attempting to accomplish? It appears that you are trying to get your Client model, which has a ForeignKey or OneToOne relationship with the Django.contrib.auth User model, into your template context. Is that correct? – Del Apr 30 '16 at 23:25
  • Yep, that's right! But the client is from url, not the online client (request.user). – A. Fynn Apr 30 '16 at 23:29

1 Answers1

2

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
markwalker_
  • 12,078
  • 7
  • 62
  • 99
  • Yes, thanks. It's work! One of the best ways, that's what I'm doing right now. But, for sure, is it the safe one? – A. Fynn Apr 30 '16 at 23:50
  • @A.Fynn There are certainly some things that you don't want to add to session data for security/privacy reasons. But I would of thought what you're doing here should be safe. Equally though, you should consider adding that to the view context because if the username is required, it'll only work for people on that URL so a context processor is overkill. – markwalker_ May 02 '16 at 00:58