【Python】Django--認證系統-登入註冊

小亮520cl發表於2017-02-28

1.modles層 與admin

點選(此處)摺疊或開啟

  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals

  3. from django.db import models
  4. from django.contrib.auth.models import AbstractUser
  5. from django.utils.encoding import python_2_unicode_compatible

  6. ###普通使用者的資料模型
  7. @python_2_unicode_compatible
  8. class NewUser(AbstractUser):
  9.     profile = models.CharField('profile', default='', max_length=256)

  10.     def __str__(self):
  11.         return self.username
  12. # Create your models here.


##admin
# -*- coding: utf-8 -*- 
from django.contrib import admin from .models import NewUser class NewUserAdmin(admin.ModelAdmin):
    list_display = ('username','date_joined', 'profile')



admin.site.register(NewUser,NewUserAdmin)


2.setting設定newuser管理系統賬號進行驗證

  1. AUTH_USER_MODEL = "pric.NewUser"

3  views檢視層

  1. # -*- coding: utf-8 -*-
  2. from django.shortcuts import render
  3. from .forms import *
  4. from .models import *
  5. from django.contrib.auth import authenticate, login, logout
  6. from django.http import HttpResponse
  7. from django.shortcuts import render, redirect,render_to_response
  8. from django.core.exceptions import ObjectDoesNotExist
  9. from django.contrib.auth.decorators import login_required



  10. @login_required
  11. def index(request):
  12.     return render_to_response('index.html', locals())




  13. ###登入
  14. def log_in(request):
  15.     if request.method == 'GET':
  16.         form = LoginForm()
  17.         return render(request, 'login.html', {'form': form})
  18.     if request.method == 'POST': # 當提交表單時
  19.         form = LoginForm(request.POST) # form 包含提交的資料
  20.         if form.is_valid(): # 如果提交的資料合法
  21.             username = form.cleaned_data['uid']
  22.             password = form.cleaned_data['pwd']
  23.             user = authenticate(username=username, password=password)  
  24.             if user is not None: ###如果使用者驗證存在,
  25.                 login(request, user) #開始登入
  26.                 return redirect('index') #跳轉首頁
  27.             else:
  28.                 return render(request, 'login.html', {'form': form, 'msg': "password or username is not ture!"})

  29.         else: ###如果提交的資料不合法,繼續登入
  30.             return render(request, 'login.html', {'form': form})

  31. ###登出
  32. @login_required
  33. def log_out(request):
  34.     logout(request)
  35.     return redirect('login')
  36. # Create your views here.

  37. ###註冊
  38. def register(request):
  39.     error1 = "this name is already exist"
  40.     valid = "this name is valid"

  41.     if request.method == 'GET':
  42.         form = RegisterForm()
  43.         return render(request, 'register.html', {'form': form})
  44.     if request.method == 'POST': ###提交
  45.         form = RegisterForm(request.POST)
  46.         if form.is_valid():
  47.                 username = form.cleaned_data['username']
  48.                 email = form.cleaned_data['email']
  49.                 password1 = form.cleaned_data['password1']
  50.                 password2 = form.cleaned_data['password2']
  51.                 if password1 != password2:
  52.                     return render(request, 'register.html', {'form': form, 'msg': "two password is not equal"})
  53.                 else:
  54.                     NewUser.objects.create_user(username=username,password=password1,email=email)
  55.                     #user = NewUser(username=username, email=email, password=password1)
  56.                     #user.save()
  57.                     # return render(request, 'login.html', {'success': "you have successfully registered!"})
  58.                     return redirect('login')
  59.         else:
  60.                 return render(request, 'register.html', {'form': form})

4 首頁獲取當前登入使用者


  1. 方式一:
    前端request.user.is_authenticated()判斷當前使用者是否登入 

  2. <form class="form-signin" role="form" method='post'>
  3.         <h2 class="form-signin-heading">Welcome!>
  4.           {% if request.user.is_authenticated %}
  5.             hihi: {{ request.user }} </br>
  6.           <a href="{% url 'log_out' %}">登出</a>
  7.           {% endif %}

  8.       </form>


方式二 將request.user.is_authenticated判斷寫入views檢視再傳入html中
  1. @login_required
  2. def index(request):
  3.     if request.user.is_authenticated(): # 判斷使用者是否已登入
  4.         user = request.user;
  5.         return render_to_response('index.html', locals())



  6.  <form class="form-signin" role="form" method='post'>
  7.         <h2 class="form-signin-heading">Welcome!>
  8.              歡迎登入!{{ user }}
  9.           <a href="{% url 'log_out' %}">登出</a>
  10.           

  11.       </form>





###本節學習的重點就是authenticate認證
參考官方文件:
http://www.cnblogs.com/holbrook/archive/2012/02/10/2357345.html

----詳細

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29096438/viewspace-2134408/,如需轉載,請註明出處,否則將追究法律責任。

相關文章