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)
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
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'
SLDEM's suggestion:
@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
question from:
https://stackoverflow.com/questions/65870615/valueerror-invalid-literal-for-int-with-base-10-slug-1-2