0

I have a button in my template but it returned None to me. What's my problem

HTML code

<form action="{% url 'blog:like_post' post.id post.slug %}">
    {% csrf_token %}
    <button type='submit',name = 'post_id', value = "{{post.id}}" class="btn btn_primary btn_sm">Like</button>
    {{ total_likes }} Likes
</form>

views.py

@login_required
def like(request, id, slug):
    pk = request.POST.get('post_id')
    print(pk)
    post = get_object_or_404(Post, id = pk)
    post.likes.add(request.user)
    return HttpResponseRedirect(reverse('blog:detail'),kwargs={'id': id, 'slug':slug})

@login_required
def DetailPost(request, id, slug):
    post = Post.objects.get(id=id, slug=slug)
    total_likes = post.total_likes()
    context = {
        'post' : post,
        'total_likes' : total_likes,
    }
    return render(request, 'blog/PostDetail.html', context)

urls.py

urlpatterns = [
    re_path(r'detail/(?P<id>[0-9]+)/(?P<slug>[-\w]+)/', DetailPost, name='detail'),
    re_path(r'like/(?P<id>[0-9]+)/(?P<slug>[-\w]+)/', like, name='like_post')
    ]

I print pk in my terminal and it's show None for value of pk

  • Does this answer your question? [What is the default form HTTP method?](https://stackoverflow.com/questions/2314401/what-is-the-default-form-http-method) – Abdul Aziz Barkat Jul 06 '21 at 08:47
  • You are making a GET request (the default method for a form as described in the suggested duplicate), you need to add `method="post"` to your form tag to make a POST request. – Abdul Aziz Barkat Jul 06 '21 at 08:48
  • Oh thanks I forgot it. –  Jul 06 '21 at 09:02

0 Answers0