我正在尝试为我的 Django 项目创建一个系统,允许用户对特定帖子发表评论。然而,这不起作用。
我尝试将代码输入到 forms.py、views.py、urls.py 和 index.html 中以处理帖子条目。然而,这反而导致了 index.html 上的提交按钮没有输入框,并且当单击该按钮时,页面会重新加载,而不会更新数据库。
forms.py:
class PostCommentForm(forms.ModelForm):
class Meta:
model = PostComment
fields = ['post_comment']
views.py:
from .forms import PostCommentForm
from .models import *
def post_comment(request, post_id):
post = get_object_or_404(Post_Data, pk=post_id)
if request.method == 'POST':
form = PostCommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.post = post
comment.save()
return redirect('/', pk=post_id)
else:
form=PostCommentForm()
return render(request, 'index.html', {'form': form})
urls.py:
from .views import create_post
urlpatterns = [
path('post/<int:post_id>/comment/', views.post_comment, name='post_comment'),
]
index.html:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit Comment</button>
</form>
models.py:
class PostComment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post_Data, on_delete=models.CASCADE)
post_comment = models.CharField(max_length=500)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Comment by {self.user} on {self.post}"
上面的代码按预期工作,但如果某些部分没有拼写错误,则会出现错误。
首先,将未知的create_post函数导入到urls.py中
from .views import post_comment
urlpatterns = [
path('post/<int:post_id>/comment/', post_comment, name='post_comment'),
]
我修改了这部分以导入并使用评论创建逻辑,post_comment。
下一个问题是views.py 的缩进。
from .forms import PostCommentForm
from .models import *
def post_comment(request, post_id):
post = get_object_or_404(Post_Data, pk=post_id)
if request.method == 'POST':
form = PostCommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.post = post
comment.save()
return redirect('/', pk=post_id)
else:
form=PostCommentForm()
return render(request, 'index.html', {'form': form})
要使 post_comment 正常工作,必须按上述方式进行更改。
在我的环境中测试时,上面的代码没有出现错误,并且按预期运行良好。