开发者

Need help getting authentication to work in all apps in a Django project

I'm starting up on Django, and am just a novice when it comes to server-side code. All of my web coding experience is in the front-end and is limited to CSS, HTML, and basic javascript. But I thought it was time to take it up a notch and le开发者_Python百科arn more about the back-end of things and decided to start here. I went through Django's starting application guide successfully. I'm not attempting to add an extension in and "soup up" the app.

I installed allauth for registration/user management. I was able to set it up and successfully register, log-in, log-out with the default templates.

However when I load up the polls application which is within the same project, it doesn't seem to work...

Code in index.html (found under templates/polls/)under polls application that doesn't work.

{% if user.is_authenticated %}
    <b>ALL GOOD</b>
{% else %}
    <b>Go sign-in first.</b>
{% endif %}

Code in sign-up.html (found under templates/account/) under accounts that does work.

{% if user.is_authenticated %}
    Good work
{% else %}
    Fail
{% endif %}

Am I missing an import statement somewhere? Why does it work in one template folder but not the other?

Thanks in advance!


try request.user.is_authenticatedinstead.


If you use RequestContext(request) and you have django.contrib.auth.context_processors.auth in your TEMPLATE_CONTEXT_PROCESSORS the user variable will be accessible on your template.

https://docs.djangoproject.com/en/dev/ref/templates/api/#django-contrib-auth-context-processors-auth

I think that made more sense in my head.

RequestContext is from from django.template import RequestContext and when you

render_to_response("mytemplate.html",
    RequestContext(request, {"other_variable": other_value, "more": True}))

or

template.render(RequestContext(request, {"other_variable": other_value, "more": True}))

Simply put: you get access to a bunch of variables without specifying them.


Edit :-

I just found you could use from django.views.generic.simple import direct_to_template instead of render_to_response

direct_to_template(request, "mytemplate.html", {"other_variable": other_value, "more": True})

It does the same as the render_to_response line I gave above.


Without more info it's hard to say, but my initial reaction is that you may not be passing the user variable to the template context in your view function.

i.e.:

def view(request):
    t = loader.get_template('index.html')
    c = Context({"user": request.user})
    return HttpResponse(t.render(c))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜