ValueError: littéral invalide pour int () avec base 10: 'slug-1-2' 2ème fois, je suis à nouveau confronté à cette erreur. J'essaie d'autoriser les utilisateurs à modifier leurs commentaires dans n'importe quel article de blog, mais il semble qu'il y ait un problème avec cette ligne: comment = get_object_or_404(Comment, id=post_id)

Cela a fonctionné pour d'autres fonctions (par exemple quand j'ai créé une fonction qui peut supprimer des commentaires) mais pas celle-ci. Une idée de la façon dont je peux résoudre ce problème? J'ai eu le sentiment que cela a à voir avec lorsque j'ajoute des commentaires dans l'url, j'utilise slug et lorsque j'édite l'url des commentaires. Mais cela a fonctionné pour ma fonction de suppression et j'ai utilisé post_id pour cette fonction. Merci

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

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'


Suggestion du 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 %}

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

-1
user14820658 24 janv. 2021 à 15:38

2 réponses

Meilleure réponse

Il semble que le problème ici est lié à votre URL , faites-le comme suit:

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

(Ajoutez la spécification que la variable transmise est en fait un entier), puis utilisez la valeur de votre Comment instance id dans votre vue .

Ok donc en fonction de vos modifications:

  1. Où vous avez votre html pour modifier le commentaire:

    {% 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 %}
    
  2. Dans votre vue où vous recevez le commentaire:

    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
    

Et ça devrait marcher.

1
SLDem 24 janv. 2021 à 15:57

L'élément <form> de votre html n'a pas d'attribut action qui devrait spécifier à quelle URL vos données de formulaire doivent être envoyées. En cas d'omission, le formulaire sera envoyé à n'importe quelle page que vous êtes. Vous devez vous assurer que l'URL à laquelle vous envoyez est au format 'editowncomments/<post_id>'. Votre erreur signifie probablement que vous envoyez un slug au lieu de post_id.

0
Glenn D.J. 24 janv. 2021 à 14:14
65870615