ValueError:以10为基数的int()的无效文字:'slug-1-2' [英] ValueError: invalid literal for int() with base 10: 'slug-1-2'

查看:39
本文介绍了ValueError:以10为基数的int()的无效文字:'slug-1-2'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ValueError:以10为底的int()的无效文字:'slug-1-2'第二次我再次面对这个错误.我试图允许用户在任何博客文章中编辑他们的评论,但此行似乎存在问题: comment = get_object_or_404(Comment,id = post_id)

ValueError: invalid literal for int() with base 10: 'slug-1-2' 2nd time i am facing this error again. I am trying to allow users to edit their comments in any blog post but it seems that there is a problem with this line: comment = get_object_or_404(Comment, id=post_id)

这对于其他功能(例如,当我创建一个可以删除注释的功能时)有效,但不适用于此功能.知道我该如何解决吗?当我在使用slug和< post_id>当我编辑评论网址时.但这对我的删除功能有效,我确实为该功能使用了post_id.谢谢

This has worked for other functions (eg when i created a function that can delete comments) but not this one. Any idea how I can resolve this? I got a feeling its sth to do with when I add comments in the url I use slug and <post_id> when I edit comments url. But it worked for my delete function and i did use post_id for that function. Thanks

models.py

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

urls.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"),

html

<form class="create-form" method="POST" enctype="multipart/form-data">{% csrf_token %}

 <div class="form-group">
  <label for="id_body">Body</label>
  <textarea class="form-control" rows="8" type="text" name="body" id="id_body" required>{{form.initial.body}}</textarea>
 </div>

 <button class="submit-button btn btn-lg btn-primary btn-block" type="submit">Edit Comment</button>


</form> 

TraceBack

TraceBack

Internal Server Error: /HomeFeed/editowncomments/slug
Traceback (most recent call last):
  File "lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "HomeFeed/views.py", line 995, in edit_own_comment
    comment = get_object_or_404(Comment, id=post_id)
  File "lib/python3.8/site-packages/django/shortcuts.py", line 93, in get_object_or_404
    return queryset.get(*args, **kwargs)
  File "/lib/python3.8/site-packages/django/db/models/query.py", line 399, in get
    clone = self.filter(*args, **kwargs)
  File "/lib/python3.8/site-packages/django/db/models/query.py", line 892, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "lib/python3.8/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1290, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1315, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "/lib/python3.8/site-packages/django/db/models/lookups.py", line 20, in __init__
    self.rhs = self.get_prep_lookup()
  File "lib/python3.8/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 972, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'slug'


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)

    path('editowncomments/<int:post_id>', edit_own_comment, name= "edit_own_comment"),

html

  {% 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 %}

详细views.py

detail views.py

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

推荐答案

看起来问题出在您的 url 上,就像这样:

Well looks like the issue here is with your url, make it like this:

path('edit-own-comments/<int:post_id>', edit_own_comment, name="edit_own_comment"),

(添加传递的变量实际上是整数的说明),然后在视图中使用 Comment 实例 id 的值

(Add the specification that the passed variable is actually an integer) And then use the value of your Comment instance id in your view.

好的,根据您的修改:

  1. html 中可以编辑评论的地方:

  1. Where you have your html to edit the 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
    

  • 它应该可以工作.

    这篇关于ValueError:以10为基数的int()的无效文字:'slug-1-2'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆