之前我问了类似的问题,但是当我认为它得到修复后,我从错误中得到错误。作为超级用户,我想创建多个类别,并限制其他类别只有一个。我已成功限制用户只发布一个,但我也只能发布一个。当我尝试这样做时,我在/ add_category /得到IntegrityError UNIQUE约束失败:main_category.author_id
这里;我的代码
models.py
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
description = models.CharField(max_length=200, unique=True)
image = models.FileField(upload_to='images',blank=True, null=True)
author = models.OneToOneField(settings.AUTH_USER_MODEL, unique=True)
def __unicode__(self):
views.py
@login_required
def add_category(request):
if not request.user.is_superuser and Category.objects.filter(author=request.user).exists():
return render(request,'main/category_already_exists.html')
if request.method == 'POST':
category = Category(author=request.user)
form = CategoryForm(request.POST, request.FILES, instance=category)
if form.is_valid():
form.save(commit=True)
return redirect('index')
else:
form = CategoryForm()
return render(request, 'main/add_category.html', {'form':form})
提前致谢
答案 0 :(得分:1)
您应该更改“作者”#39;字段到 ForeignKeyField
一对一的关系。从概念上讲,这类似于具有唯一= True的ForeignKey,但关系的“反向”将直接返回单个对象。
models.py
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
description = models.CharField(max_length=200, unique=True)
image = models.FileField(upload_to='images',blank=True, null=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL)
def __unicode__(self):