Question

This view function:

@login_required 
def dashboard(request):
    from myproject.myapp.models import UserProfile
    k = UserProfile.objects.get( user=request.user.pk ).known

    return render_to_response('dashboard.html', {'KNOWN': k, , context_instance=RequestContext(request))

Passes to this template:

{% if user.is_authenticated %}
    {{ user.username }}
{% else %}
    Login link
{% endif %}
    {{ KNOWN }}
  1. I have already logged in.
  2. Page does not redirect to LOGIN_URL (so therefore @login_required thinks im logged in I guess)
  3. {{ KNOWN }} renders perfectly OK
  4. {{ user.username }} doesn't appear

How is this possible? Surely if login_required works, and it managed to grab KNOWN, therefore user must exist somewhere?
How can I debug this?

:-)


UPDATE: If I remove:

TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.request',)

From settings, it works.
However, by removing that, other pages which use {{ request.get_full_path }} in templates don't load.
Eeek.


UPDATE 2:

TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.request",)

If you just add the request line on its own, it disables all the others which are defaults. D'Oh!


UPDATE 3: Thought that would fix it, unfortunately still not working.


UPDATE 4: Spotted typo elsewhere, can confirm that Mark Lavin's answer fixed it :)

Was it helpful?

Solution

If you are setting TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.request',) then you are removing all the default context processors in particular django.contrib.auth.context_processors.auth which adds user to the context. You should instead use

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
)

OTHER TIPS

You should keep django.core.context_processors.request, it allows to use the {{ request }} in templates.

The request object features a user property which should correspond to the user requesting the page.

Try this, it should work for you too:

{% if request.user.is_authenticated %}
    you're authenticated as {{ request.user.username }}
{% else %}
    i'm a guest
{% endif %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top