简体   繁体   English

IntegrityError at /create/ NOT NULL 约束失败:main_post.author_id

[英]IntegrityError at /create/ NOT NULL constraint failed: main_post.author_id

When i try to create an new post with http://localhost:8000/create/, i get this error.当我尝试使用 http://localhost:8000/create/ 创建新帖子时,我收到此错误。 I couldn't find the solution thought they seem similar.我找不到认为它们看起来相似的解决方案。 I follows some blog tutorial我遵循一些博客教程

I can't paste the settings.py here because there to much code in the post but i think the settings.py is fine btw我无法在此处粘贴 settings.py,因为帖子中有很多代码,但我认为 settings.py 很好,顺便说一句

My models.py (* i deleted some code maynot involve)我的models.py (*我删除了一些可能不涉及的代码)

User = get_user_model()

class Author(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_picture = models.ImageField()

    def __str__(self):
        return  self.user.username

class Post(models.Model):
    title = models.CharField(max_length=100)
    overview = models.TextField()
    detail = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    content = RichTextUploadingField(config_name='post_ckeditor')
    comment_count = models.IntegerField(default=0)
    view_count = models.IntegerField(default=0)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    thumbnail = models.ImageField()
    categories = models.ManyToManyField(Category)
    featured = models.BooleanField()
    previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank = True, null = True)
    next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank = True, null = True)

My views.py我的观点.py

def get_author(user):
    qs = Author.objects.filter(user=user)
    if qs.exists():
        return qs[0]
    return None
    pass

def post_create(request):
    form = PostForm(request.POST or None, request.FILES or None)
    author= get_author(request.user)
    if request.method == 'POST':
        if form.is_valid():
            form.instance.author = author
            form.save()
            return redirect(reverse('post-detail', kwargs={
                'id': form.instance.id
                }))
    context = {
        'form': form
    }
    return render(request, 'post_create.html', context)
    pass

My forms.py我的 forms.py

from django import forms
from .models import Post, Comment


class PostForm(forms.ModelForm):
    content = forms.CharField
    class Meta:
        model = Post
        fields = ('title', 'overview', 'content', 'thumbnail', 'categories', 'featured', 'previous_post', 'next_post')

class CommentForm(forms.ModelForm):
    content = forms.CharField(widget=forms.Textarea(attrs={
        'class':'form-control',
        'placeholder':'Type your comment',
        'id':'usercomment',
        'rows':4
    }))
    class Meta:
        model = Comment
        fields = ('content', )

Please help !请帮忙 !

Whenever there is a change in model fields or new model added or removed, you should migrate.每当 model 字段发生更改或添加或删除新的 model 时,您都应该迁移。 And pass a default object to foreign key if not null.如果不是 null,则将默认 object 传递给外键。

If you are trying to save request.user in the author field you don't need to write the extra methods just do like this.如果您尝试将request.user保存在 author 字段中,则不需要编写额外的方法,只需这样做。

if request.method == 'POST':
    if form.is_valid():
       post =form.save(commit=False)
       post.author = request.user
       post.save()
       return redirect(reverse('post-detail', kwargs={'id': post.id }))

暂无
暂无

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

相关问题 /users/create/ 处的 IntegrityError | NOT NULL 约束失败:users_post.author_id | Django Web 应用程序 - IntegrityError at /users/create/ | NOT NULL constraint failed: users_post.author_id | Django Web App / admin / main / category / add / NOT NULL约束处的IntegrityError失败:main_category.author_id - IntegrityError at /admin/main/category/add/ NOT NULL constraint failed: main_category.author_id 我在 /post/new/ NOT NULL 约束失败处收到 IntegrityError:blog_post.author_id - I'm getting an IntegrityError at /post/new/ NOT NULL constraint failed: blog_post.author_id IntegrityError at /post/new/ NOT NULL 约束失败:blog_post.author_id - IntegrityError at /post/new/ NOT NULL constraint failed: blog_post.author_id django.db.utils.IntegrityError:NOT NULL 约束失败:home_post.author_id - django.db.utils.IntegrityError: NOT NULL constraint failed: home_post.author_id Django:NOT NULL 约束失败:new__create_post.author_id - Django: NOT NULL constraint failed: new__create_post.author_id 唯一约束失败:django 中的 new__main_post.author_id - UNIQUE constraint failed: new__main_post.author_id in django /posts/12/new-comment/ NOT NULL 约束失败的 IntegrityError:posts_comment.author_id - IntegrityError at /posts/12/new-comment/ NOT NULL constraint failed: posts_comment.author_id /admin/main/post/add/ NOT NULL 约束的 IntegrityError 失败:main_post.status - IntegrityError at /admin/main/post/add/ NOT NULL constraint failed: main_post.status Django IntegrityError 'author_id' 违反了非空约束 - Django IntegrityError 'author_id' violates not-null constraint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM