# -*- coding:utf-8 -*-
from django.contrib import admin
from django.contrib.auth.models import User
from django_admin.models import Employee
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import make_password
from django.utils.translation import ugettext, ugettext_lazy as _
class EmployeeInline(admin.StackedInline):
model = Employee
can_delete = False
max_num = 1
class MyModelAdmin(admin.ModelAdmin):
inlines = (EmployeeInline, )
# list_display = ('username','department',)
# def department(self,obj):
# return '%s'%obj.employee.department
# def get_queryset(self, request):
# return User.objects.filter(employee__department=request.user.employee.department).order_by('id')
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'password')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
admin.site.unregister(User)
admin.site.register(User, MyModelAdmin)
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
department = models.CharField(max_length=100)
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
class Department(models.Model):
department = models.CharField(max_length=100)
class Employee(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
department = models.ForeignKey(Department,on_delete=models.CASCADE)
save_model(request, obj, form, change)
此方法为admin界面用户保存model实例时的行为。request为HttpRequest实例,obj为model实例,form为ModelForm实例,change为bool值,取决于model实例是新增的还是修改的。
重写此方法可以做一些pre-save或者post-save行为。
比如,可以把request.user保存为model实例的属性:
from django.contrib import adminclass ArticleAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user obj.save()