简体   繁体   English

django,FOREIGN KEY约束失败

[英]FOREIGN KEY constraint failed , django

I have to insert the post through a form but when i submit i got this error FOREIGN KEY constraint failed, the problem is with the author field 我必须通过表单插入帖子但是当我提交我得到此错误FOREIGN KEY约束失败时,问题出在作者字段

models.py 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 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 forms.py

class PostForm(forms.ModelForm):

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

template 模板

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

如果作者字段是问题,请确保导入auth.User

My guess is that you are trying to add the post as anonymous but anonymous user is not null (id is though). 我的猜测是你试图将帖子添加为匿名,但匿名用户不是null(虽然id是)。 Also don't use 'auth.User' and follow the instructions from the documentation . 也不要使用'auth.User'并按照文档中的说明进行操作。

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

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