Unable to use slug instead of pk

Hello there, am trying to add a Liking functionality to my blog posts using only python without Ajax or the rest. I added a ‘likes’ attribute with a ManyToManyField to my Post model. here is the view function that concerns the Like feature

def LikeView(request, slug):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    post.likes.add(request.user)
    return HttpResponseRedirect(reverse('post_detail', args=[str(slug)]))
class PostDetailView(generic.DetailView):
    model = Post
    template_name = 'blog/post_detail.html'

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)

        stuff = get_object_or_404(Post, id=self.kwargs['slug']) #here is the particular line that get called up
        total_likes = stuff.total_likes()
        context["total_likes"] = total_likes
        return context

I replaced pk with slug because pk always throws errors whenever I used it. here is the url path;

path('like/<int:slug>/', views.LikeView, name='like_post'),

Here is the part of my post_details.html template that displays the like feature;

<div class="text-left">
                          <form action="{% url 'post_likes' post.slug %}" method="POST">
                              {% csrf_token %}
                              <button type="submit", name="post_id", value="{{ post.id }}", class="btn btn-primary btn-lg">
                                  <span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> Like
                              </button> - {{ total_likes }} Likes
                          </form>
                      </div>

but then when I click the Readmore link to the post-detail page, i get this error

ValueError at /blogpost-7/
Field 'id' expected a number but got 'blogpost-7'.
Request Method:	GET
Request URL:	http://127.0.0.1:8000/blogpost-7/
Django Version:	3.0.8
Exception Type:	ValueError
Exception Value:
Field 'id' expected a number but got 'blogpost-7'.
Exception Location:	C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 1774

I can`t seem to fix this error

Here is an example of one of my URLs where I use a slug.

    path("<slug:slug>", SiteTextDetailView.as_view(), name="site_text_detail"),

Slug is probably a slug field in your models and as such the URL expects to be fed a slug in its path.

In your get_context_data() method you have the following

Is the id of your Post a slugfield?

This is the problem. You’ve specified that your “slug” field is going to be an integer, when it’s not. It’s getting passed the string blogpost-7 and can’t convert it.

It was giving the same error when I used ‘slug:slug/’

I have a slug field in my Post model, but I didn’t specify it as the post id. But I always use the slug in my URLs since PK throws errors

Ahh, also noticed, something isn’t matching up.

The URL you’re posting:
path('like/<int:slug>/', views.LikeView, name='like_post'),

has the name like_post and has the path starting with a component like/

But the template fragment you posted:

Is referencing the name post_likes, and generates a URL without the like/ component.

This is actually a typo from when I was posting the question, the url name in the template tag on my work is ‘like_post’…

I have also changed the /int:slug to like/slug:slug yet

Please don’t retype things. Copy and paste from the files / terminal session. We need to see what is causing errors, and we can only debug from the information provided.

1 Like