我终于找到了一种方法来实现我所需要的。它可能不是最干净的,并且可以接受建议,但它可能会帮助遇到类似问题的人。
由于我只需要从管理员创建,我专注于此并构建以下内容。
表格.py
class RequiredInlineFormSet(BaseInlineFormSet):
"""
Generates an inline formset that is required
"""
def _construct_form(self, i, **kwargs):
"""
Override the method to change the form attribute empty_permitted
"""
form = super(RequiredInlineFormSet, self)._construct_form(i, **kwargs)
form.empty_permitted = False
self.can_delete = False
return form
models.py(我没有使用信号在用户创建时自动创建配置文件)
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
[.......]
USER_TYPES = (
('manager', 'Manager'),
('employee', 'Employee'),
)
user_type = models.CharField(blank=True, max_length=10, choices=USER_TYPES)
def __unicode__(self):
return self.user.username
class EmployeeProfile(UserProfile):
[...]
def __init__(self, *args, **kwargs):
super(EmployeeProfile, self).__init__(*args, **kwargs)
self.user_type = 'employee'
class ManagerProfile(UserProfile):
[...]
def __init__(self, *args, **kwargs):
super(ManagerProfile, self).__init__(*args, **kwargs)
self.user_type = 'manager'
class Manager(User):
class Meta:
proxy = True
#app_label = 'auth'
verbose_name = 'manager'
verbose_name_plural = 'managers'
def save(self, *args, **kwargs):
self.is_staff = True
super(Manager, self).save(*args, **kwargs) # Call the "real" save() method.
g = Group.objects.get(name='Managers')
g.user_set.add(self)
class Employee(User):
class Meta:
proxy = True
#app_label = 'auth'
verbose_name = 'employee'
verbose_name_plural = 'employees'
def save(self, *args, **kwargs):
self.is_staff = False
super(Employee, self).save(*args, **kwargs) # Call the "real" save() method.
g = Group.objects.get(name='Employees')
g.user_set.add(self)
管理员.py
class ManagerProfileAdmin(admin.StackedInline):
model = ManagerProfile
max_num = 1
extra = 1
formset = RequiredInlineFormSet
class EmployeeProfileAdmin(admin.StackedInline):
model = EmployeeProfile
max_num = 1
extra = 1
formset = RequiredInlineFormSet
class ManagerAdmin(UserAdmin):
"""
Options for the admin interface
"""
inlines = [ManagerProfileAdmin]
def queryset(self, request):
qs = super(UserAdmin, self).queryset(request)
qs = qs.filter(Q(userprofile__user_type='manager'))
return qs
class EmployeeAdmin(UserAdmin):
"""
Options for the admin interface
"""
inlines = [EmployeeProfileAdmin]
def queryset(self, request):
qs = super(UserAdmin, self).queryset(request)
qs = qs.filter(Q(userprofile__user_type='employee'))
return qs
admin.site.unregister(User)
admin.site.register(Manager, ManagerAdmin)
admin.site.register(Employee, EmployeeAdmin)