Django抱怨字段在编辑条目时不是唯一的

时间:2013-03-14 01:24:00

标签: django django-models django-admin

models.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)

admin.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密钥已经存在。",即使这是使用此密钥的唯一条目。如果我更新任何字段,我怎样才能使这个字段独一无二,但不要抱怨?谢谢!

1 个答案:

答案 0 :(得分:0)

使用OSQA的BaseModel类来解决这个问题,可以在这里找到源代码: https://github.com/Syerram/osqa/blob/master/forum/models/base.py