我不明白,哪里出了问题。 你能告诉我吗?我需要调整哪一项?
/blog/15/ 处的值错误 ModelForm 没有指定模型类。
我需要调整哪一项?
我想知道解决办法
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", )
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}"
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())
]
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
你应该在 html 页面中像这样定义 {{ comment_form.as_p }}