python - 如何解决 FieldError - 无法将关键字“slug”解析为字段
问题描述
我正在制作一个帖子和评论模型。我创建了 Post and Comment 模型,看起来还不错。我可以添加帖子并评论任何特定的帖子。我正在尝试为每个发表评论的用户提供删除它的选项
这是views.py
def delete_comment(request):
id = request.POST['comment_id']
pk = request.POST['post_id']
if request.method == 'POST':
comment = get_object_or_404(Comment, id=id, pk=pk)
try:
comment.delete()
messages.success(request, 'You have successfully deleted the comment')
except:
messages.warning(request, 'The comment could not be deleted.')
return redirect('blog:post-detail')
这是模板:
<form action = "{% url 'blog:post-commentd' %}" method = "POST">
{% csrf_token %}
<input type="hidden" name="comment_id" value="{{ comment.id }}"/>
<input type="hidden" name="post_id" value="{{ post.id }}"/>
<button class="btn btn-danger btn-sm mt-1 mb-1">Delete</button>
</form>
这是网址
path('blog/delete_comment/',
delete_comment, name='post-commentd'),
这是models.py
class Post(models.Model):
title = models.CharField(max_length=100, unique=True)
content = RichTextUploadingField(null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
slug = models.SlugField(blank=True, null=True, max_length=120)
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
content = models.TextField(max_length=300, validators=[validate_comment_text])
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now=True)
解决方案
如果我是你,我会使用链接而不是表单来删除评论,并确保只有评论的作者才能看到删除按钮。这就是我尝试这样做的方式。
{% if comment.name == user.username %}
<button class="btn btn-danger btn-sm mt-1 mb-1"
onclick="location.href='{% url 'blog:delete-comment' comment.id
%}';">Delete</button>
{% endif %}
我的网址应该是这样的
path('blog/delete_comment/<int:id>/',
views.delete_comment, name='delete-comment'),
然后我的views.py
@login_required
def delete_comment(request,id):
comment = get_object_or_404(Comment,id=id)
slug = comment.post.slug
try:
if request.user == comment.user:
comment.delete()
messages.success(request, 'You have successfully deleted the
comment')
except:
messages.warning(request, 'The comment could not be deleted.')
return redirect('blog:post-detail', slug)
推荐阅读
- python - Keras:使用 model.train_on_batch() 和 model.fit() 获得不同的准确度。可能是什么原因以及如何解决?
- java - 包括来自不同于根目录的 .pde 文件
- highcharts - Highcharts:水平条形图中条形上方的 xAxis 标签
- javascript - 为 .ajaxError() 中重新发送的 Ajax 请求执行 .done() 函数
- r - 将 Web 服务中的折线添加到 R 传单地图
- python - 将字典写入 Sql 表,代码执行没有任何问题,但值没有绑定到 SQL 表中
- elasticsearch - 衰减函数内的术语过滤器
- reactjs - 如何在加载时打开 React Native Maps 标记的标注
- java - NoSuchAlgorithmException[1.2.840.113549.1.1.1 KeyFactory 不可用];
- python - 无法从“img”标签中提取“src”属性