当前位置: 首页 > 工具软件 > Admin > 使用案例 >

user_admin

欧阳智志
2023-12-01
 
  
  1. # -*- coding:utf-8 -*-
  2. from django.contrib import admin
  3. from django.contrib.auth.models import User
  4. from django_admin.models import Employee
  5. from django.contrib.auth.backends import ModelBackend
  6. from django.contrib.auth.hashers import make_password
  7. from django.utils.translation import ugettext, ugettext_lazy as _
  8. class EmployeeInline(admin.StackedInline):
  9. model = Employee
  10. can_delete = False
  11. max_num = 1
  12. class MyModelAdmin(admin.ModelAdmin):
  13. inlines = (EmployeeInline, )
  14. # list_display = ('username','department',)
  15. # def department(self,obj):
  16. # return '%s'%obj.employee.department
  17. # def get_queryset(self, request):
  18. # return User.objects.filter(employee__department=request.user.employee.department).order_by('id')
  19. fieldsets = (
  20. (None, {'fields': ('username', 'password')}),
  21. (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
  22. 'groups', 'password')}),
  23. (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
  24. )
  25. admin.site.unregister(User)
  26. admin.site.register(User, MyModelAdmin)


 
   
  1. # -*- coding: utf-8 -*-
  2. from django.db import models
  3. from django.contrib.auth.models import User
  4. class Employee(models.Model):
  5. user = models.OneToOneField(User,on_delete=models.CASCADE)
  6. department = models.CharField(max_length=100)


 
   
  1. # -*- coding: utf-8 -*-
  2. from django.db import models
  3. from django.contrib.auth.models import User
  4. class Department(models.Model):
  5. department = models.CharField(max_length=100)
  6. class Employee(models.Model):
  7. user = models.OneToOneField(User,on_delete=models.CASCADE)
  8. 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()























转载于:https://www.cnblogs.com/wuqingzangyue/p/5749664.html

 类似资料:

相关阅读

相关文章

相关问答