首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django唯一约束失败: webapp_post.slug

Django唯一约束失败: webapp_post.slug
EN

Stack Overflow用户
提问于 2016-04-13 04:56:19
回答 1查看 2K关注 0票数 1

当我试图创建一个新的Post对象时,Python输出了以下错误:

代码语言:javascript
复制
UNIQUE constraint failed: webapp_post.slug

这是我的models.py

代码语言:javascript
复制
class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    text = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    up_vote = 0 # num of up votes
    down_vote = 0 #num of down votes
    vote_total = up_vote - down_vote
    author = models.ForeignKey('auth.User', null=True, blank=True)

    CHOICES = [
        ('Hardware and OS', 'Hardware and OS'),
        ('Desktops', 'Desktops'),
        ('Tablets', 'Tablets'),
        ('Phones', 'Phones'),
        ('Wearables', 'Wearables'),
        ('Windows', 'Windows'),
        ('Mac OS X', 'Mac OS X'),
        ('Linux and Unix', 'Linux and Unix'),
        ('Programming and Computer Science', 'Programming and Computer Science'),
        ('Software Development', 'Software Development'),
        ('Web Development (Front)', 'Web Development (Front)'),
        ('Web Development (Back)', 'Web Development (Back)'),
        ('Mobile Development', 'Mobile Development'),
        ('Game Development', 'Game Development'),
        ('Algorithms and Data Structures', 'Algorithms and Data Structures'),
        ('Databases', 'Databases'),
        ('IDE / Text Editors', 'IDE / Text Editors'),
        ('Tutorial', 'Tutorial'),
        ('Opinion', 'Opinion'),
        ('Miscellaneous', 'Miscellaneous')
    ]
    field = models.CharField(choices=CHOICES, max_length=200)

    def __unicode__(self):
        return self.title

    @models.permalink
    def get_absolute_url(self):
        return ('blog_post_detail', (), 
                {
                    'slug' :self.slug,
                })

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

这是我的views.py

代码语言:javascript
复制
@user_passes_test(lambda u: u.is_authenticated)
def add_post(request):
    form = PostForm(request.POST or None)

    if request.method == "POST":
        if form.is_valid() and request.user.is_authenticated():
            try:
                post = form.save(commit=False)
                post.author = request.user
                post.save()
                Post.objects.create(author=request.user, title=form.cleaned_data.get("title"), text=form.cleaned_data.get("text"))
                return redirect(post)
            except IntegrityError as e:
                print(e)
        else:
            print("Invalid form")
            print(form.errors)

    return render_to_response('webapp/startthread.html', 
                              { 'form': form,
                                "authenticated": request.user.is_authenticated() },
                              context_instance=RequestContext(request))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-13 05:24:01

Django报告说,数据库不会保存Post数据,因为另一个Post已经在使用slug字段的值。

如果不希望这种行为,请不要在模型中将unique属性设置为Post.slug上的True。不过,请考虑一下,slug通常用于查询数据库以查找相关的Post,因此通常您希望它是唯一的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36588911

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档