python3 django 實現后台用戶登錄,項目瀏覽權限管理。


項目需求:

python 3.6

django 2.0

mysql

win10

源碼地址:https://github.com/a715506891/login

主要目的:

用戶需要登錄才能進入項目進行瀏覽

對相應視圖進行權限管理,對應賬戶才能進行相關瀏覽

結合自帶后台對用戶進行管理分組

主要用途:

后台數據管理及查看。

應用前提:

首先建立自己的項目

實現步驟:

創建login文件

建立projiect和app

在cmd輸入以下代碼

 1 django-admin startproject myprojiect 2 cd .\myprojiect\ 3 python manage.py startapp myapp 

在myapp中建立templates文件

在setting中加入myapp

 

在templates下新建文件

index.html輸入

<h1>總頁面</h1>
<a href="{% url 'num1' %}">第一</a>
<a href="{% url 'num2' %}">第二</a>

 

numone.html輸入

<h1>第一個頁面</h1>
<a href="{% url 'index' %}">總頁面</a>
<a href="{% url 'num2' %}">第二</a>

 

numtwo.html輸入

<h1>第二個頁面</h1>
<a href="{% url 'index' %}">總頁面</a>
<a href="{% url 'num1' %}">第一</a>

 

在myapp下的views.py中加入

from django.shortcuts import render

# Create your views here.


def index(request):
    return render(request, 'index.html')


def numone(request):
    return render(request, 'numone.html')


def numtwo(request):
    return render(request, 'numtwo.html')

在urls中加入

"""myprojiect URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from myapp import views as myapp_views  # 加載app

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', myapp_views.index, name='index'),
    url(r'^num1/$', myapp_views.numone,
        name='num1'),
    url(r'^num2/$', myapp_views.numtwo,
        name='num2'),
]

在命令行執行

python manage.py runserver

 

訪問 http://127.0.0.1:8000/

建立后台,可以查看官方文檔 http://python.usyiyi.cn/documents/django_182/intro/tutorial02.html

先在命令行運行以下命令。建立配置

python manage.py makemigrations

 python manage.py migrate

 

創建一個管理員用戶
首先,我們需要創建一個能夠登錄管理站點的用戶。 運行如下命令:
$ python manage.py createsuperuser
鍵入你想要使用的用戶名,然后按下回車鍵:
Username: admin
然后提示你輸入想要使用的郵件地址:
Email address: admin@example.com
你需要輸入兩次密碼,第二次輸入是確認密碼
Password: **********
Password (again): *********
Superuser created successfully.

在命令行執行

python manage.py runserver

訪問 http://127.0.0.1:8000/admin 進行登錄

 

登錄以后可以在

訪問自己寫的網站

在index.html,numone.html,numtwo.html中分別加入

<a href="http://127.0.0.1:8000/admin">后台</a>

 

在numone.html增加登錄用戶權限

將views.py文件修改為

from django.shortcuts import render
from django.contrib.auth.decorators import login_required  # 權限
# Create your views here.


def index(request):
    return render(request, 'index.html')

@login_required(login_url='/admin/login/')# 增加訪問權限,需要去哦用戶登錄才能查看視圖,如果沒有登錄返回登錄界面
def numone(request):
    return render(request, 'numone.html')


def numtwo(request):
    return render(request, 'numtwo.html')

訪問http://127.0.0.1:8000/admin退出用戶登錄

再訪問http://127.0.0.1:8000/

點擊第一個跳轉到注冊頁面,需要登錄才能查看。其他頁面沒加限制可以正常訪問

 

登錄用戶限制訪問權限

官方教程 http://python.usyiyi.cn/documents/django_182/topics/auth/default.html

登錄后台添加用戶 admin1

勾選

保存

修改views.py文件

 

from django.shortcuts import render
from django.contrib.auth.decorators import login_required  # 登陸權限
from django.contrib.auth.decorators import permission_required  # 登陸訪問權限

# Create your views here.


def index(request):
    return render(request, 'index.html')


@login_required(login_url='/admin/login/')
def numone(request):
    return render(request, 'numone.html')


@login_required(login_url='/admin/login/')
@permission_required('myapp.add', login_url='/num1/')#如果具有myapp.add權限可以訪問頁面2,否則返回頁面1
def numtwo(request):
    return render(request, 'numtwo.html')

退出登錄

命令行運行

python manage.py runserver

訪問 http://127.0.0.1:8000/

點擊第二

用admin 登錄可以正常訪問

退出admin,重復場面步驟,點擊第二

用admin1登錄,點擊第二會跳轉到第一個頁面

 

后篇自定義權限:

在models.py中加入

 1 from django.db import models
 2 
 3 # Create your models here.
 4 
 5 
 6 class Question(models.Model):
 7     question_text = models.CharField(max_length=200)
 8     pub_date = models.DateTimeField('date published')
 9 
10     def __str__(self):              # __unicode__ on Python 2
11         return self.question_text
12 
13 
14 class Choice(models.Model):
15     question = models.ForeignKey(Question, on_delete=models.CASCADE)
16     # 即在外鍵值的后面加上 on_delete=models.CASCADE
17     choice_text = models.CharField(max_length=200)
18     votes = models.IntegerField(default=0)
19 
20     class Meta:
21         permissions = (
22             ("can_drive", "Can drive"),#新的自定義權限
23             ("can_vote", "Can vote in elections"),
24             ("can_drink", "Can drink alcohol"),
25         )
26 
27     def __str__(self):              # __unicode__ on Python 2
28         return self.choice_text

在admin.py中加入

 1 from django.contrib import admin
 2 
 3 from .models import Choice, Question
 4 
 5 
 6 class ChoiceInline(admin.TabularInline):
 7     model = Choice
 8     extra = 3
 9 
10 
11 class QuestionAdmin(admin.ModelAdmin):
12     fieldsets = [
13         (None,               {'fields': ['question_text']}),
14         ('Date information', {'fields': [
15          'pub_date'], 'classes': ['collapse']}),
16     ]
17     inlines = [ChoiceInline]
18     #list_display = ('question_text', 'pub_date')
19     #list_display = ('question_text', 'pub_date', 'was_published_recently')
20 
21 admin.site.register(Question, QuestionAdmin)

先在命令行運行以下命令。建立配置

python manage.py makemigrations

 python manage.py migrate

 執行運行命令

 python manage.py runserver

訪問后台,登陸admin,點擊user,點擊admin

 

 

有新加入的權限

 

權限實現是自己想的,不知道對不對,反正是能夠實現分組管理了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM