我有一个名为Fruits的应用,有两个用户,分别是卖方和买方。每个用户类型都有一个不同的字段:
卖方有字段
买方有字段
因为每个用户都有电话号码字段,所以我在Django用户模型中像这样创建此字段;
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Master
class User(AbstractUser):
telephone = models.PositiveIntegerField(null=True, blank=True)
class Meta:
permissions = (
("seller", "Seller"),
("buyer", "Buyer"),
)
# Seller
class Customer(models.Model):
user = models.OneToOneField(User, verbose_name="user_id", db_column="user_id", related_name="profile", on_delete=models.CASCADE)
location = models.CharField(max_length=255, null=True)
shop_name = models.CharField(max_length=255, null=True)
open_hours = models.TextField(max_length=500, null=True)
# Buyer
class Customer(models.Model):
user = models.OneToOneField(User, verbose_name="user_id", db_column="user_id", related_name="profile", on_delete=models.CASCADE)
address = models.TextField(max_length=500, null=True)
并在 admin.py 中;
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.forms import TextInput, Textarea, NumberInput
from django.db import models
from .models import User
from .models import Seller
from .models import Buyer
admin.site.register(User)
class SellerProfileInline(admin.StackedInline):
model = Seller
can_delete = False
verbose_name = "Seller Profile"
verbose_name_plural = "Seller Profile"
fk_name = "user"
class BuyerProfileInline(admin.StackedInline):
model = Buyer
can_delete = False
verbose_name = "Buyer Profile"
verbose_name_plural = "Buyer Profile"
fk_name = "user"
class CustomUser(UserAdmin):
inlines = [SellerProfileInline, BuyerProfileInline]
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'telephone')
fieldsets = (
(None, {'fields': ('username', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name', 'email', 'telephone')}),
('Permissions', {
'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
}),
('Important dates', {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'groups', 'user_permissions'),
}),
)
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size':40})},
models.PositiveIntegerField: {'widget': NumberInput(attrs={'size':10})},
models.TextField: {'widget': Textarea(attrs={'rows':4, 'cols':40})},
}
admin.site.unregister(User)
admin.site.register(User, CustomUser)
它可以工作,但是卖方和买方的字段全部显示在底部的编辑配置文件页面中。我希望每个用户角色都有一个特定的模型,所以要有不同的字段。
说明;
首先,用户创建管理员选择角色,为此,我将移动选择组和角色/权限以添加用户页面(请参见add_fieldsets
)。
但是,在用户个人资料中会出现来自两个模型(卖方和买方)的字段。我想按角色分开每个字段。因此,字段Location, Shop Name, Open Hours
出现在具有角色Seller
的用户上。字段Address
出现在具有角色Buyer
的用户上。
如何制作。