简体   繁体   English

Django UNIQUE约束失败:webapp_post.slug

[英]Django UNIQUE constraint failed: webapp_post.slug

When I'm trying to create a new Post object, Python spews out the following error: 当我尝试创建新的Post对象时,Python喷出以下错误:

UNIQUE constraint failed: webapp_post.slug

Here is my models.py 这是我的models.py

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)

Here is my views.py 这是我的views.py

@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))

Django is reporting that the database will not save your Post data because the value of the slug field is already being used by another Post . Django报告说该数据库将不会保存您的Post数据,因为slug字段的值已被另一个Post

If you don't want this behaviour, do not set the unique attribute to True on Post.slug in your model. 如果您不希望这种行为,请不要在模型中的Post.slug unique属性设置为True Consider though, that the slug is often used to query the database to find the associated Post , so generally you'll want it to be unique. 但是请考虑一下,该slug通常用于查询数据库以找到关联的Post ,因此通常您希望它是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM