Почему я получаю нулевую ошибку ограничения? - PullRequest
0 голосов
/ 03 октября 2018

Я пытаюсь добавить комментарии к фактам (сообщениям).Когда я пытаюсь оставить комментарий, я получаю следующую ошибку?Я использую Postgres FYI

IntegrityError at /fc/2/comment/
null value in column "comment_id" violates not-null constraint
DETAIL:  Failing row contains (8, It has plugins too, 2018-10-03 07:41:25.249524+00, 1, null).

Exception Value:    
null value in column "comment_id" violates not-null constraint
DETAIL:  Failing row contains (8, It has plugins too, 2018-10-03 07:41:25.249524+00, 1, null).

Модель:

class Fact(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
        default=timezone.now)
    published_date = models.DateTimeField(
        blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Comment(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    comment = models.ForeignKey('fc.Fact', on_delete=models.CASCADE, related_name='comments')
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)

Вид:

def add_comment_to_post(request,pk):
fc = get_object_or_404(Fact, pk=pk)
if request.method =="POST":
    form =CommentForm(request.POST)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.fc = fc
        comment.save()
        return redirect('fc_detail',pk=fc.pk)
else:
    form =CommentForm()
return render(request,'add_comment_to_post.html',{'form':form})

Вид формы:

{% extends 'base.html' %}

{% block content %}

    <h1>Check this fact</h1>
    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>
    </form>

{% endblock %}

Форма:

class FcForm(forms.ModelForm):

class Meta:
    model = Fact
    fields = ('title', 'text',)

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('author', 'text',)

Почему значение comment_id равно нулю, я бы подумал, что Django автоматически заполняет это так же, как и в моей модели Fact.

Оцените помощь по этому вопросу.

Спасибо.

1 Ответ

0 голосов
/ 03 октября 2018

Это должно быть

comment<b>.comment</b> = fc

вместо

comment.fc = fc


, следовательно, ваше мнение будет

def add_comment_to_post(request, pk):
    fc = get_object_or_404(Fact, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            <b>comment.comment = fc # change is here <<<</b>
            comment.save()
            return redirect('fc_detail', pk=fc.pk)
    else:
        form = CommentForm()
    return render(request, 'add_comment_to_post.html', {'form': form})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...