Reputation: 2268
I'm trying to get into Django and got stuck with DeatailView
and RedirectView
I made the following template for rendering posts with enabling post detailed view and like button. When I click on either Like
or Detail
button none of the requests is sent. I tried changing different methods, but that didn't help either. I trying to get whether I was mistaken in the template or in view logic.
{% extends 'base.html' %}
{% block content %}
{% for post in object_list %}
<div class="card" style="width: 40rem;">
<img src = "{{ post.image.url }}" style="height: 40rem;">
<div class="card-body">
<h5 class="card-tittle">{{post.author.username}}</h5>
<p class="card-text">{{ post.description }}</p>
<p class="card-text">Likes : {{ post.likes.count }}</p>
<p class="id">Post_id: {{ post.id }}</p>
<div class="btn-group-vertical">
{% if user.is_authenticated %}
<form action="{% url 'like_post' %}" method="POST">
{% csrf_token %}
<button type="button" class="btn btn-secondary">Like</button>
</form>
{% endif %}
<form action="{% url 'detail' pk=post.id %}" method="GET">
<button type="button" class="btn btn-secondary">Detail</button>
</form>
<!-- <button type="button" class="btn btn-secondary">down</button> -->
</div>
</div>
</div>
{% endfor %}
{% endblock %}
Posts views.py
file
class PostDetail(DetailView):
model = Post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
print(context.items())
return context
class PostLikeUpvote(RedirectView):
def get_redirect_url(self, *args, **kwargs):
post_id = kwargs.get('id')
post = get_object_or_404(Post, id=post_id)
user = self.request.user
if user.is_authenticated():
post.likes.add(user)
url_redirect = post.get_redirect_url()
return url_redirect
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('new/', PostCreate.as_view(), name='new'),
path('', PostList.as_view(), name='list'),
path('posts/', PostList.as_view(), name='list'),
path('like_post/', PostLikeUpvote.as_view(), name='like_post'),
path('posts/<pk>/', PostDetail.as_view(), name='detail'),
path('bot/webhook', csrf_exempt(BotView.as_view())),
]
Any comments are appreciated.
Upvotes: 1
Views: 187
Reputation: 477607
In order to submit the form, the type of the button should be submit
, not button
:
{% if user.is_authenticated %}
<form action="{% url 'like_post' %}" method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-secondary">Like</button>
</form>
{% endif %}
otherwise it is a simple button that can for example run a JavaScript function, but it will not (automatically) submit the form. Of course you can write a JavaScript function to submit the form, but unless you have a specific reason for that, it is better to let the browser do the work for you.
Upvotes: 1