Python ValueError:以10为基数的int()的文本无效:';slug-1-2';
ValueError:基数为10的int()的文本无效:“slug-1-2” 第二次我再次面临这个错误。我试图允许用户在任何博客文章中编辑他们的评论,但这一行似乎有问题:Python ValueError:以10为基数的int()的文本无效:';slug-1-2';,python,django,django-models,django-views,django-forms,Python,Django,Django Models,Django Views,Django Forms,ValueError:基数为10的int()的文本无效:“slug-1-2” 第二次我再次面临这个错误。我试图允许用户在任何博客文章中编辑他们的评论,但这一行似乎有问题: comment=get\u object\u或\u 404(comment,id=post\u id) 这对其他函数(例如,当我创建一个可以删除注释的函数时)有效,但对这个函数无效。你知道我该怎么解决这个问题吗?当我在我使用slug的url中添加评论和编辑评论url时,我有一种感觉。但它对我的delete函数有效,我确实使用了
comment=get\u object\u或\u 404(comment,id=post\u id)
这对其他函数(例如,当我创建一个可以删除注释的函数时)有效,但对这个函数无效。你知道我该怎么解决这个问题吗?当我在我使用slug的url中添加评论和编辑评论url时,我有一种感觉。但它对我的delete函数有效,我确实使用了post_id来实现该函数。谢谢
models.py
class Comment(models.Model):
post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE)
name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE)
body = models.TextField()
class BlogPost(models.Model):
title = models.CharField(max_length=50, null=False, blank=False, unique=True)
body = models.TextField(max_length=5000, null=False, blank=False)
slug = models.SlugField(blank=True, unique=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
views.py
def edit_own_comment(request, post_id):
context = {}
comment = get_object_or_404(Comment, id=post_id)
if request.method == 'POST':
form = UpdateCommentForm(request.POST, instance=comment)
if comment.name == request.user and form.is_valid():
obj = form.save(commit=False)
obj.save()
messages.success(request, 'Your comment has been edited', extra_tags='editedcomment')
return redirect(reverse("HomeFeed:detail", kwargs={'slug': comment.post.slug }))
form = UpdateCommentForm(
initial = {
"body": comment.body,
}
)
context['form'] = form
return render(request, 'HomeFeed/edit_comment.html', context)
class AddCommentView(LoginRequiredMixin, DetailView, FormView):
login_url = 'must_authenticate'
model = BlogPost
form_class = CommentForm
template_name = 'HomeFeed/add_comment.html'
def form_valid(self, form):
comment = form.save(commit=False)
comment.name = self.request.user
comment.post = self.get_object()
comment.save()
return redirect(reverse("HomeFeed:detail", kwargs={'slug': comment.post.slug }))
def delete_any_comment(request, post_id):
if request.method == 'POST':
comment = get_object_or_404(Comment, id=post_id)
if comment.post.author == request.user:
comment.delete()
return redirect(reverse("HomeFeed:detail", kwargs={'slug': comment.post.slug }))
forms.py
class UpdateCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['body']
def save(self, commit=True):
comment = self.instance
comment.body = self.cleaned_data['body']
if commit:
comment.save()
return comment
url.py
path('comments/<slug>', AddCommentView.as_view(), name= "add_comment"),
path('editowncomments/<post_id>', edit_own_comment, name= "edit_own_comment"),
path('deleteanycomments/<post_id>', delete_any_comment, name= "deleteanycomments"),
SLDEM的建议:
@login_required(login_url=reverse_lazy("must_authenticate"))
def edit_own_comment(request, post_id):
context = {}
comment = get_object_or_404(Comment, id='slug')
if comment.name != request.user:
return HttpResponse('You did not write the comment.')
if request.method == 'POST':
form = UpdateCommentForm(request.POST or None, instance=comment)
if comment.name == request.user and form.is_valid():
obj = form.save(commit=False)
#this prints a success message after it is safe
obj.save()
return redirect(reverse("HomeFeed:detail", kwargs={'slug': comment.post.slug }))
form = UpdateCommentForm(
initial = {
"body": comment.body,
}
)
context['form'] = form
return render(request, 'HomeFeed/edit_comment.html', context)
看起来这里的问题在于您的url,如下所示:
path('edit-own-comments/<int:post_id>', edit_own_comment, name="edit_own_comment"),
{% if comment.name == request.user %}
<a class="btn btn-sm btn-warning col-lg-4" href="{% url 'HomeFeed:edit_own_comment' comment.id %}">Edit comment</a> <!-- here change comment_id to comment.id to pass the correct value to the url -->
{% endif %}
comment = get_object_or_404(Comment, id=post_id) # also rename post_id to something like comment_id here and in the url to make it more readable
它应该能工作。错误到底是什么时候发生的?哈哈,我的救世主,它发生在这行代码中
comment=get\u object\u或\u 404(comment,id=post\u id)
在编辑\u own\u comment视图下其他代码都能工作,只有这行代码不工作。你需要追踪吗?那会很有帮助的yes@SLDem添加兄弟,不知道为什么slug会显示,即使我使用了post_id。我感觉这与我在url中添加评论和编辑评论时使用slug有关。但我不太确定如何将其重新命名。我也在delete comment视图中使用了post_id,它很有效。Hi bro正在添加int,因为我不必为其他URL添加int@SLDem,还有,您介意演示如何使用注释实例id的值吗?你的意思是post\u id=post\u id吗?你使用的url是/HomeFeed/editowncomments/slug
,而不是传递id
(它是一个int)你传递了str类型的'slug',因此出现了错误,你用id='slug'
:)来查询你的评论,所以我所要做的就是更改url?然后在我的模板上,它将是
是的,但是post\u id
参数实际上必须类似于comment\u id
,因为您正在使用ITI bro查询注释,sry ah lemme编辑我的代码,您可以看到我是否理解您的意思
{% if not blog_post.comments.all %}
<p>No comments yet... Add a <a href="{% url 'HomeFeed:add_comment' blog_post.slug %}">comment</a></p>
{% else %}
<a href="{% url 'HomeFeed:add_comment' blog_post.slug %}">Add a comment</a>
<br>
{% for comment in blog_post.comments.all %}
<strong>
{{ comment.name}}
{{ comment.date_added }}
</strong>
{{ comment.body }}
{% if comment.name == request.user and blog_post.author != request.user %}
<form action = "{% url 'HomeFeed:deletecomments' comment.id %}" method = "POST"> {% csrf_token %}
<button class="btn btn-sm btn-danger">Delete</button>
</form>
{% endif %}
{% if blog_post.author == request.user %}
<form action = "{% url 'HomeFeed:deleteanycomments' comment.id %}" method = "POST"> {% csrf_token %}
<button class="btn btn-sm btn-danger">Delete</button>
</form>
{% endif %}
{% if comment.name == request.user %}
<a class="btn btn-sm btn-warning col-lg-4" href="{% url 'HomeFeed:edit_own_comment' comment_id %}">Edit comment</a>
{% endif %}
{% endfor %}
{% endif %}
class DetailBlogPostView(BlogPostMixin,DetailView):
template_name = 'HomeFeed/detail_blog.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
blog_post=self.get_object()
blog_post.save()
context['blog_post'] = blog_post
account = Account.objects.all()
context['account'] = account
#aka if blog post does belong to me
if blog_post.author != self.request.user:
if self.request.user.is_authenticated and \
blog_post.interest_set.filter(user__id=self.request.user.id).exists():
submittedinterest = True
context["interest_pk"]=blog_post.interest_set.first().pk
#if blog post belongs to me
else:
submittedinterest = False
context['submittedinterest'] = submittedinterest
if blog_post.interest_set.exists():
context["interest_pk"]=blog_post.interest_set.first().pk
return context
path('edit-own-comments/<int:post_id>', edit_own_comment, name="edit_own_comment"),
{% if comment.name == request.user %}
<a class="btn btn-sm btn-warning col-lg-4" href="{% url 'HomeFeed:edit_own_comment' comment.id %}">Edit comment</a> <!-- here change comment_id to comment.id to pass the correct value to the url -->
{% endif %}
comment = get_object_or_404(Comment, id=post_id) # also rename post_id to something like comment_id here and in the url to make it more readable