【问题标题】:IntegrityError at /create/ NOT NULL constraint failed: main_post.author_id/create/ NOT NULL 约束处​​的 IntegrityError 失败:main_post.author_id
【发布时间】:2020-07-20 16:55:32
【问题描述】:

当我尝试使用 http://localhost:8000/create/ 创建新帖子时,我收到此错误。我找不到认为它们看起来相似的解决方案。我遵循一些博客教程

我无法在此处粘贴 settings.py,因为帖子中有很多代码,但我认为 settings.py 很好,顺便说一句

我的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)

我的意见.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

我的表单.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', )

请帮忙!

【问题讨论】:

    标签: python python-3.x django django-models django-forms


    【解决方案1】:

    如果您尝试将request.user 保存在作者字段中,则无需编写额外的方法,只需这样做即可。

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

    【讨论】:

      【解决方案2】:

      每当模型字段发生更改或添加或删除新模型时,您都应该迁移。如果不为空,则将默认对象传递给外键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 2023-03-29
        • 1970-01-01
        • 2020-12-19
        • 2016-04-02
        • 2020-08-01
        • 2021-06-27
        相关资源
        最近更新 更多