【问题标题】:FOREIGN KEY constraint failed , djangoFOREIGN KEY 约束失败,django
【发布时间】:2019-04-18 11:21:56
【问题描述】:

我必须通过表单插入帖子,但是当我提交时出现此错误 FOREIGN KEY constraint failed,问题出在作者字段

models.py

class Post(models.Model):
    STATUS_CHOICES = (
        ('draft','Draft'),
        ('published','Published'),
    )

    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=120)
    author = models.ForeignKey('auth.User',related_name='blog_posts',on_delete=models.CASCADE,blank=True, null=True)
    body = RichTextField()
    created = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
    tag = models.OneToOneField(Tag,related_name="blog_tag",on_delete=models.CASCADE,default=0)

    def __str__(self):
        return self.title

views.py

def tagView(request,name):
    tag = Tag.objects.get(name=name)
    post_form = PostForm(request.POST or None)
    if request.method == 'POST':
        post_form = PostForm(request.POST)
        if post_form.is_valid():
            item = post_form.save(commit=False)
            item.author = request.user
            item.save()

            return HttpResponseRedirect(request.path_info)
    context = {
        'post_form' : post_form,
        'tag' : tag,
    }
    return render(request,'blog/tagPage.html',context)

forms.py

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ['title','body']

模板

<form class="post-form" method="POST" enctype="multipart/form-data" action="">
    {% csrf_token %}
    {{ post_form }}
    <input class="post-form-submit submit" type="submit" value="Save">
  </form>

【问题讨论】:

  • 显示完整错误。你确定作者是问题吗?
  • 保存Post 实例时必须设置tag 属性,但您的表单和视图都没有定义它。

标签: python django


【解决方案1】:

如果作者字段有问题,一定要导入auth.User

【讨论】:

    【解决方案2】:

    我的猜测是您正在尝试将帖子添加为匿名但匿名用户不为空(虽然是 id)。也不要使用'auth.User' 并按照documentation 的说明进行操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 2022-10-17
      • 2019-11-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多