我是Django的新手。我目前正在尝试为我的应用程序中的每个帖子实现评论部分。我在尝试删除特定注释并获取错误时遇到错误int()参数必须是字符串或数字,而不是' SimpleLazyObject'。这是我的代码。
comment.html:
<h3> Comments </h3>
{% get_comment_count for post as comment_count %}
<p>This post has {{ comment_count }} comments.</p>
{% get_comment_list for post as comment_list %}
{% for comment in comment_list %}
<div style="border: 1px solid green;">
<a name="c{{ comment.id }}"></a>
<a href="{% get_comment_permalink comment %}">
permalink for comment #{{ forloop.counter }}
</a>
<hr>
<h4> Just for testing purpose (Ignore) </h4>
<p> content_object : {{comment.content_object.id}}</p>
<p> content_type : {{comment.content_type}}</p>
<p> object_pk(Foreign Key) : {{comment.object_pk}} </p>
<p> user(Foreign Key) : {{comment.user}}</p>
<p> Comment ID : {{comment.id}}</p>
<hr>
<p>Posted by: {{ comment.user_name }} on {{ comment.submit_date }}</p>
<p> {{comment.comment}}</p>
<!-- NOT SURE HOW WILL IT WORK -->
<a href = '{% url 'delete_own_comment' comment.id %}'> Delete Comment </a>
</div>
{% endfor %}
Views.py
import django_comments
from django_comments.models import Comment
from django_comments.views.moderation import perform_delete
def delete_own_comment(request, comment_id):
comment = get_object_or_404(Comment, id=comment_id)
# if comment.user.id != request.user.id:
# raise Http404
perform_delete(request, comment)
但是,我注意到如果我在get_object_or_404的参数中给出任何错误的comment_id,它会让我进入404页面,但是当正确的comment_id被传递时,它会给我错误
Request Method: GET
Request URL: http://localhost:8080/posts/comments/delete/2/
Django Version: 1.8.2
Exception Type: TypeError
Exception Value:
int() argument must be a string or a number, not 'SimpleLazyObject'
Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py in get_prep_value, line 985
Python Executable: /usr/bin/python
Python Version: 2.7.6
2)此外,在html中,评论链接的永久链接不起作用。它也给我404错误:
post objects don't have a get_absolute_url() method
但是,我的帖子模型中确实有get_absolute_url():
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.id})
url.py
# ex: /posts/3/
url(r'^(?P<post_id>[0-9]+)/$', views.detail, name='post-detail'),
答案 0 :(得分:0)
我不在我的工作笔记本电脑前,但这应该有效:
comment = get_object_or_404(YourCommentModel.id, id=comment_id) #assuming the pk for Comment is id
此外,请确保您正在调用评论并将其分配给您的模型,如
YourCommentModel = models.ForeignKey(Comment)
我可能错了,但您从未将django_comment分配给模型(或者未在问题中包含模型),这是必需的,否则表格不会添加到您的数据库中