/create_post/ 处的 Django IntegrityError

Django IntegrityError at /create_post/

尝试创建基于 class 的视图时,我得到上面列出的 IntegrityError 完整错误是

IntegrityError at /create_post/
null value in column "author_id" of relation "blog_post" violates not-null constraint
DETAIL:  Failing row contains (6, First, 2021-02-27 15:36:47.072327+00, Cosndfadfa, 2021-02-27 15:36:47.072447+00, null).

我不确定我做错了什么。非常感谢对此的任何帮助。

下面是我的views.py

class CreateView(CreateView):
    model = Post
    template_name = "blog/post_form.html"
    fields = ["title", "content"]

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("about/", views.about, name="about"),
    path("blog/", views.BlogList.as_view(), name="blog-list"),
    path("create_post/", views.CreateView.as_view(), name="create"),
]

我的 post 模型在 models.py

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


class Post(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    updated_on = models.DateTimeField(auto_now=True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_on"]

    def __str__(self):
        return self.title

和我的post_form.py

{%extends "blog/base.html"%}
{% load crispy_forms_tags %}

{%block content%}

<div class="container">
    <main class="form-signin">
        <form method="POST">
            {%csrf_token%}
          <h1 class="h3 mb-3 fw-normal">Create New Post </h1>
            {{form|crispy}}
          <button class="w-15 btn btn-lg btn-primary" type="submit">Create </button>
        </form>
      </main>
    </div>

{%endblock content%}

非常感谢对此的任何帮助。

您需要为 author 指定一个值,因为这是一个不可为 NULL 的字段并且没有默认值。您可以通过覆盖 form_valid 方法来做到这一点:

from django.contrib.auth.mixins import <b>LoginRequiredMixin</b>

class CreateView(<b>LoginRequiredMixin</b>, CreateView):
    model = Post
    template_name = 'blog/post_form.html'
    fields = ['title', 'content']

    def form_valid(self, form):
        form<b>.instance.author = self.request.user</b>
        return super().form_valid(form)

Note: You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc].