How to properly use the django built-in login view

2019-04-21 06:56发布

I'm just getting started with Django, and I'm trying to use built-in features as much as possible. As such, for user login, I'm using the built-in login view, and assigning it to the base url of my site:

urlpatterns=patterns('django.contrib.auth.views',
    url(r'^/$','login',{'template':'mytemplate.html'}),

mytemplate.html looks something like this:

<!DOCTYPE html>
<html>
<body>
    {%if form.errors %}
    <p> Invalid username/password combination, please try again </p>
    {% endif %}

    <h1>Welcome to My Site!</h1>
    <form action="{% url django.contrib.auth.views.login %}" method="post">
    {% csrf_token %}
        {{form.username.label_tag}}{{form.username}}
        {{form.password.label_tag}}{{form.password}}
        <input type="submit" id="submit" name="submit" value="Sign in" />
        <input type="hidden" name="next" value="{{ next }}" />        
    </form>
    <a href="password_reset/" id="forgot"> forgot username/password</a><br />
    <a href="register" id="new">new user</a>
</body>
</html>

my problem is, the template doesn't appear to be getting passed any of the context it's supposed to. In the rendered HTML, all of my variable tags simply disappear (i.e. rather than being replaced by the appropriate values, thay are replaced with nothing).

I imagine I'm skipping some critical step, but I can't figure out what it is. Any ideas?

2条回答
孤傲高冷的网名
2楼-- · 2019-04-21 07:38

You need to change from 'template' to 'template_name'

urlpatterns=patterns('django.contrib.auth.views',
    url(r'^/$','login',{'template_name':'mytemplate.html'}),

https://docs.djangoproject.com/en/1.4/topics/auth/#django.contrib.auth.views.login

查看更多
做自己的国王
3楼-- · 2019-04-21 07:52

Try removing the template name from your url configuration. Django will then fall back to a standard template, that way you can see if you screwed up the template somehow or if something else is wrong.

My next guess would be to check your settings for the TEMPLATE_CONTEXT_PROCESSORS. If you have defined any of them, be sure to include

"django.contrib.auth.context_processors.auth",

If you haven't defined any, django will use a standard tuple, which allready includes the auth processor.

查看更多
登录 后发表回答