首页 > 解决方案 > NOT NULL 约束失败:community_comment.posts_id?

问题描述

我该如何解决这个问题?
页面运行完美。当我发布帖子时。它发布但是当我想输入评论并通过“GET”发送时,我收到了这个错误。那么,我如何才能在我的第一个问题中忽略此错误?
- 另外,我需要任何人给我最好的方式来建立帖子和评论之间的关系

模型.py

from django.db import models
from django.contrib.auth.models import User


class Publication(models.Model):
    title = models.CharField(max_length=30)

    class Meta:
        ordering = ['title']

    def __str__(self):
        return self.title


class Article(models.Model):
    publications = models.ManyToManyField(Publication)
    headline = models.CharField(max_length=100)

    class Meta:
        ordering = ['headline']

    def __str__(self):
        return self.headline


class Post(models.Model):
    users = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    question = models.TextField(max_length=500)

    def __str__(self):
        return self.title


class Comment(models.Model):
    posts = models.ForeignKey(Post, on_delete=models.CASCADE)
    comment = models.TextField(max_length=500)

    def __str__(self):
        return self.comment

视图.py

from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Post, Comment
from .forms import PostForm, CommentForm


def index(request):
    # All questions
    posts = Post.objects.all()
    return render(request, 'community/index.html', {'posts': posts})


def post_view(request):
    post_form = PostForm
    context = {'posted': post_form}

    # Create post
    if request.method == 'GET':
        post_form = PostForm(request.GET)
        if post_form.is_valid():
            user_post = post_form.save(commit=False)
            user_post.title = post_form.cleaned_data['title']
            user_post.question = post_form.cleaned_data['question']
            post = Post.objects.create(users=User.objects.get(username=request.user), title=user_post.title, question=user_post.question)
            post.save()
            return redirect('community:index')

    return render(request, 'community/post.html', context)


def answers(request, post_id):
    # Specific post
    posts = Post.objects.get(id=post_id)
    # Create comment
    comment_form = CommentForm
    context = {'posts': posts, 'comment_form': comment_form}
    if request.method == 'GET':
        comment_form = CommentForm(request.GET)
        if comment_form.is_valid():
            user_comment = comment_form.save(commit=False)
            user_comment.comment = comment_form.cleaned_data['comment']
            user_comment.save()

    return render(request, 'community/answers.html', context)

网址.py

from django.urls import path
from . import views

app_name = 'community'

urlpatterns = [
    path('', views.index, name='index'),
    path('post/', views.post_view, name='post'),
    path('answers/<int:post_id>', views.answers, name='answers'),
]

表格.py

from .models import Post, Comment
from django import forms
from django.contrib.auth.models import User


class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = '__all__'
        exclude = ['users']


class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = '__all__'
        exclude = ['users', 'posts']

标签: pythondjango

解决方案


您忘记分配您创建的评论的post或:post_id

def answers(request, post_id):
    # Specific post
    posts = Post.objects.get(id=post_id)
    # Create comment
    comment_form = CommentForm
    context = {'posts': posts, 'comment_form': comment_form}
    if request.method == 'GET':
        comment_form = CommentForm(request.GET)
        if comment_form.is_valid():
            comment_form.instance.post_id = post_id
            user_comment = comment_form.save()
    # …

话虽如此,上述观点并没有真正尊重 HTTP 假设。发出 GET 请求的视图应该更改实体,因此如果要创建评论,则需要通过 POST 请求来完成。此外,为了实现Post/Redirect/Get模式 [wiki],一个成功的POST 请求应该返回一个重定向响应。


推荐阅读