我该如何解决? django - ValueError:ModelForm 没有指定模型类

问题描述 投票:0回答:1

我不明白,哪里出了问题。 你能告诉我吗?我需要调整哪一项?

/blog/15/ 处的值错误 ModelForm 没有指定模型类。

错误信息图片

我需要调整哪一项?

我想知道解决办法

博客/forms.py

from .models import Comment
from django import forms

class CommentForm(forms.ModelForm):
    class Mata:
        model = Comment
        fields = ("content", )
        # exclude = ("post", "author", "created_at", "modified_at", )

博客/models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.author}::{self.content}"

    def get_absolute_url(self):
        return f"{self.post.get_absolute_url()}#comment-{self.pk}"

博客/urls.py

from django.urls import path
from . import views


urlpatterns = [
    # FBV 방식의 패턴
    # path('', views.index),
    # path('<int:pk>/', views.single_post_page)

    # CBV 방식의 패턴
    path("", views.PostList.as_view()),
    path("<int:pk>/", views.PostDetail.as_view()),
    path("category/<str:slug>/", views.category_page),
    path("tag/<str:slug>/", views.tag_page),
    path("<int:pk>/new_comment/", views.new_comment),
    path("create_post/", views.PostCreate.as_view()),
    path("update_post/<int:pk>/", views.PostUpdate.as_view())

]

博客/views.py

def new_comment(request, pk):
    if request.user.is_authenticated:
        post = get_object_or_404(Post, pk=pk)

        if request.method == "POST":
            comment_form = CommentForm(request.POST)
            if comment_form.is_valid():
                comment = comment_form.save(commit=False)
                comment.post = post
                comment.author = request.user
                comment.save()
                return redirect(comment.get_absolute_url())
        else:
            return redirect(post.get_absolute_url())
    else:
        raise PermissionDenied
django
1个回答
0
投票

你应该在 html 页面中像这样定义 {{ comment_form.as_p }}

© www.soinside.com 2019 - 2024. All rights reserved.