Сбой ограничения NOT NULL: community_comment.posts_id? - PullRequest
1 голос
/ 16 февраля 2020

как я могу решить эту проблему?
страница работает отлично. когда я публикую пост. он публикует сообщения, но когда я хочу напечатать комментарий и отправить «GET», я получаю эту ошибку. Итак, как я могу игнорировать эту ошибку в этом моем первом вопросе?
- также мне нужен кто-нибудь, чтобы дать мне лучший способ установить связь между постом и комментарием

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

views.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)

urls.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'),
]

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

1 Ответ

2 голосов
/ 16 февраля 2020

Вы забыли назначить 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():
            <b>comment_form.instance.post_id = post_id</b>
            user_comment = comment_form.save()
    # &hellip;

При этом вышеприведенное представление на самом деле не соответствует предположениям HTTP. Представление, которое делает запрос GET, , а не должно изменять сущности, поэтому, если вы хотите создать комментарий, вы должны сделать это с помощью запроса POST. Кроме того, для реализации шаблона Post / Redirect / Get [wiki] a успешно POST-запрос должен возвращать ответ перенаправления.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...