简体   繁体   中英

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

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

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). Also don't use 'auth.User' and follow the instructions from the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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