django 사용자 로그인 및 종료

4851 단어 django
urls.py
from django.conf.urls import url
from users.views import LoginView,LogoutView

urlpatterns = [
    url(r'^login/$', LoginView.as_view(),name="login"),
    url(r'^logout/$', LogoutView.as_view(),name="logout"),
    ……
]

forms.py
class LoginForm(forms.Form):
    username=forms.CharField(required=True)
    password=forms.CharField(required=True,min_length=5)

views.py
from django.http.response import HttpResponse,HttpResponseRedirect
from django.shortcuts import render
from django.contrib.auth import authenticate,login,logout
from django.views.generic.base import View
from django.core.urlresolvers import reverse

from .froms import LoginForm


class LogoutView(View):
    """
        
    """
    def get(self,request):
        logout(request)
        return HttpResponseRedirect(reverse("index"))



class LoginView(View):
    """
        
    """
    def get(self,request):
        return render(request, 'login.html')

    def post(self,request):
        login_form=LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get('username', None)
            pass_word = request.POST.get('password', None)
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(reverse("index"))
               else:
                    return render(request, "login.html", {"msg": "     "})
            else:
                return render(request, "login.html", {"msg": "        "})
        else:
            return render(request, "login.html", {"login_form":login_form})

좋은 웹페이지 즐겨찾기