Django 실전 사용자 인증(사용자 로그 인 및 로그아웃)
우선,사용자 로그 인 폼(forms.py)을 정의 합 니 다.
from django import forms
from django.contrib.auth.models import User
from bootstrap_toolkit.widgets import BootstrapDateInput, BootstrapTextInput, BootstrapUneditableInput
 
class LoginForm(forms.Form):
  username = forms.CharField(
    required=True,
    label=u"   ",
    error_messages={'required': '      '},
    widget=forms.TextInput(
      attrs={
        'placeholder':u"   ",
      }
    ),
  )  
  password = forms.CharField(
    required=True,
    label=u"  ",
    error_messages={'required': u'     '},
    widget=forms.PasswordInput(
      attrs={
        'placeholder':u"  ",
      }
    ),
  )  
  def clean(self):
    if not self.is_valid():
      raise forms.ValidationError(u"          ")
    else:
      cleaned_data = super(LoginForm, self).clean()다음은 사용자 로그 인 보기(views.py)를 정의 합 니 다.이 보기 에서 정의 한 사용자 로그 인 폼 을 예화 합 니 다.
from django.shortcuts import render_to_response,render,get_object_or_404 
from django.http import HttpResponse, HttpResponseRedirect 
from django.contrib.auth.models import User 
from django.contrib import auth
from django.contrib import messages
from django.template.context import RequestContext
 
from django.forms.formsets import formset_factory
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
 
from bootstrap_toolkit.widgets import BootstrapUneditableInput
from django.contrib.auth.decorators import login_required
 
from .forms import LoginForm
 
def login(request):
  if request.method == 'GET':
    form = LoginForm()
    return render_to_response('login.html', RequestContext(request, {'form': form,}))
  else:
    form = LoginForm(request.POST)
    if form.is_valid():
      username = request.POST.get('username', '')
      password = request.POST.get('password', '')
      user = auth.authenticate(username=username, password=password)
      if user is not None and user.is_active:
        auth.login(request, user)
        return render_to_response('index.html', RequestContext(request))
      else:
        return render_to_response('login.html', RequestContext(request, {'form': form,'password_is_wrong':True}))
    else:
      return render_to_response('login.html', RequestContext(request, {'form': form,}))1.필수 항목 의 사용자 이름과 비밀번호 가 비어 있 는 지 판단 하고,비어 있 으 면'사용자 이름과 비밀 번 호 는 필수 항목'이라는 오류 정 보 를 알려 줍 니 다.
2.사용자 이름과 비밀번호 가 맞 는 지 판단 하고 오류 가 발생 하면'사용자 이름 또는 비밀번호 오류'의 오류 정 보 를 알려 줍 니 다.
3.로그 인 성공 후 홈 페이지 에 들 어가 기(index.html)
그 중에서 로그 인 페이지 의 템 플 릿(login.html)은 다음 과 같이 정의 합 니 다.
<!DOCTYPE html>
{% load bootstrap_toolkit %}
{% load url from future %}
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>         </title>
  <meta name="description" content="">
  <meta name="author" content="   ">
  {% bootstrap_stylesheet_tag %}
  {% bootstrap_stylesheet_tag "responsive" %}
  <style type="text/css">
    body {
      padding-top: 60px;
    }
  </style>
  <!--[if lt IE 9]>
  <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
  {% bootstrap_javascript_tag %}
  {% block extra_head %}{% endblock %}
</head>
 
<body>
 
  {% if password_is_wrong %}
    <div class="alert alert-error">
      <button type="button" class="close" data-dismiss="alert">×</button>
      <h4>  !</h4>        
    </div>
  {% endif %}  
  <div class="well">
    <h1>         </h1>
    <p> </p>
    <form class="form-horizontal" action="" method="post">
      {% csrf_token %}
      {{ form|as_bootstrap:"horizontal" }}
      <p class="form-actions">
        <input type="submit" value="  " class="btn btn-primary">
        <a href="/contactme/" rel="external nofollow" rel="external nofollow" ><input type="button" value="    " class="btn btn-danger"></a>
        <a href="/contactme/" rel="external nofollow" rel="external nofollow" ><input type="button" value="   ?" class="btn btn-success"></a>
      </p>
    </form>
  </div>
 
</body>
</html>
  (r'^accounts/login/$', 'dbrelease_app.views.login'),1)브 라 우 저 에 입력http://192.168.1.16:8000/accounts/login/,아래 로그 인 인터페이스 출현:
 
 2)사용자 이름 이나 비밀번호 가 비어 있 을 때"사용자 이름과 비밀 번 호 는 필수 항목"이 라 고 알려 줍 니 다.다음 과 같 습 니 다.
 
 3)사용자 이름 이나 비밀번호 가 잘못 되 었 을 때'사용자 이름 이나 비밀번호 오류'를 알려 줍 니 다.다음 과 같 습 니 다.
 
 4)사용자 이름과 비밀번호 가 모두 맞다 면 홈 페이지(index.html)에 들 어가 세 요.
login 이 있 는 이상 당연히 logout 이 있어 야 합 니 다.logout 은 비교적 간단 합 니 다.Django 자체 사용자 인증 시스템 의 logout 을 직접 호출 한 다음 에 로그 인 인터페이스 로 돌아 갑 니 다.구체 적 으로 다음 과 같 습 니 다(views.py).
@login_required
def logout(request):
  auth.logout(request)
  return HttpResponseRedirect("/accounts/login/")urls.py 에 추가:
(r'^accounts/logout/$', 'dbrelease_app.views.logout'),이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Django 라우팅 계층 URLconf 작용 및 원리 해석URL 구성(URLconf)은 Django가 지원하는 웹 사이트의 디렉토리와 같습니다.그것의 본질은 URL과 이 URL을 호출할 보기 함수 사이의 맵표입니다. 위의 예제에서는 URL의 값을 캡처하고 위치 매개 변수로...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.