Django - admin後臺、auth權限
阿新 • • 發佈:2018-06-08
djang AC eat art 語言 創建 mode col class
admin後臺篇
一、創建一個管理員用戶
(1).設置時區、語言(可選步驟)
打開settings.py,改成下面那樣
LANGUAGE_CODE = ‘zh-Hans‘ TIME_ZONE = ‘Asia/Shanghai‘View Code
(2).執行命令python manage.py createsuperuser
(3).按提示輸入用戶名、郵箱、密碼(密碼至少需要8位)
(4).啟動服務,訪問 127.0.0.1:8000/admin 即可進入站點管理
二、向admin註冊模型
#----------admin.py--------- from django.contrib importView Codeadmin # Register your models here. from .models import Department,Student,Course admin.site.register(Department) admin.site.register(Student) admin.site.register(Course)
三、自定義管理頁面
Django提供了admin.ModelAdmin類通過定義ModelAdmin的子類,來定義模型在Admin界面的顯示方式
(一).列表頁屬性
(1).list_display:顯示字段,可以點擊列頭進行排序
(2).list_filter:過濾字段,過濾框會出現在右側
(3).search_fields:搜索字段,搜索框會出現在上側
(4).list_per_page:分頁,分頁框會出現在下側
(二).示例
(1).先寫好模型
#-----models.py------ class Department(models.Model): d_id = models.AutoField(primary_key=True) d_name = models.CharField(max_length=30) def __str__(self): return ‘Department<d_id=%s,d_name=%s>View Code‘%( self.d_id,self.d_name ) class Student(models.Model): s_id = models.AutoField(primary_key=True) s_name = models.CharField(max_length=30) department = models.ForeignKey(‘Department‘) course = models.ManyToManyField(‘Course‘) def __str__(self): return ‘Student<s_id=%s,s_name=%s>‘%( self.s_id,self.s_name ) class Course(models.Model): c_id = models.AutoField(primary_key=True) c_name = models.CharField(max_length=30) def __str__(self): return ‘Course<c_id=%s,c_name=%s>‘%( self.c_id,self.c_name )
(2).在該模型的app中的admin.py
# -----------admin.py-------- from django.contrib import admin # Register your models here. from .models import Department,Student,Course class DepartmentAdimin(admin.ModelAdmin): list_display = [‘d_id‘,‘d_name‘] list_display_links = [‘d_id‘,‘d_name‘] list_filter = [‘d_id‘] search_fields = [‘d_name‘] class StudentAdimin(admin.ModelAdmin): list_display = [‘s_id‘,‘s_name‘] list_display_links = [‘s_id‘,‘s_name‘] class CourseAdmin(admin.ModelAdmin): list_display = [‘c_id‘,‘c_name‘] list_display_links = [‘c_id‘,‘c_name‘] list_per_page = 5 admin.site.register(Department,DepartmentAdimin) admin.site.register(Student,StudentAdimin) admin.site.register(Course,CourseAdmin)View Code
auth權限篇
一、使用視圖方式創建一個超級用戶
from django.contrib.auth.models import User User.objects.create_user(username="yyyyyy",password="yyyyyy",email="[email protected]")View Code
二、驗證用戶
不需要再用之前的filter().first()方式了,直接用django封裝好的方法
from django.contrib.auth import authenticate user = authenticate(username=username,password=password)View Code
Django - admin後臺、auth權限