django authentication

django authentication
django session expiry

login and logout view.py

from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render
def user_login(request):
    if request.method == "POST":
        # try:
        #     m = models.UserProfile.objects.get(email=request.POST['username'])
        # except Exception:
        #     print("username doesn't exist")
        #     return render(request, "login.html")
        username = request.POST["username"]
        password = request.POST["password"]
        print(username, password)
        user = authenticate(request, email=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                # request.session.set_expiry(1800)
                return render(request, "index1.html")
            else:
                return render(request, "login.html")
        else:
            return render(request, "login.html")


def user_logout(request):
    logout(request)
    return render(request, "login.html")
    # try:
    #     del request.session['member_id']
    # except KeyError:
    #     pass

login index.html

<form method="post" class="m-t" role="form" action="{% url 'login' %}">
    {% csrf_token %}
    <div class="form-group">
        <input placeholder="Username" name="username">
    </div>
    <div class="form-group">
        <input placeholder="Password" name="password">
    </div>
    <input type="submit" value="login" >
    <input type="hidden" name="next" value="{{ next }}" />
    <p><a href="{% url 'password_reset' %}">Lost password?</a></p>
</form>

logout.html

<a href="{% url 'logout' %}">
    <i class="fa fa-sign-out">注销</i> 
</a>

urls.py

urlpatterns = [
    url(r'^login/', views.user_login, name="login"),
    url(r'^logout/', views.user_logout, name="logout"),
]
posted @ 2018-04-10 23:29  随便了888  阅读(246)  评论(0编辑  收藏  举报