模型.py
class SwagKey(BaseModel):
key = models.CharField(max_length=255, unique=True, blank=False)
keytype = models.CharField(max_length=255, default="tshirt")
user = models.ForeignKey(User, null=True, blank=True, default=0)
管理员.py
class SwagForm(ModelForm):
keytype = forms.ChoiceField(widget = forms.Select(), choices = ([('tshirt','tshirt'), ('jacket','jacket'),('backpack','backpack'), ]), initial='3', required = True,)
class Meta:
model = SwagKey
class SwagAdmin(admin.ModelAdmin):
list_display = ['key','keytype', 'user']
fieldsets = [
("Keys", {"fields": ['key', 'keytype']}),
("User", {"fields": ['user']})
]
form = SwagForm
admin.site.register(SwagKey, SwagAdmin)
当我创建一个条目时,一切都很好。但是,当我尝试编辑以将“密钥”分配给用户时,它会抱怨“带有此密钥的 Swag 密钥已经存在。”,即使这是使用此密钥的唯一条目。如果我更新其任何字段,如何使该字段唯一但不抱怨?谢谢!