【发布时间】:2021-03-20 13:12:04
【问题描述】:
我是 Django 新手,正在尝试在博客应用程序中实现喜欢和不喜欢选项。
我有一个问题,一旦任何登录用户单击“赞”按钮,浏览器就会给出 HTTP ERROR 405
一旦用户点击 Like 按钮,它就会重定向到 PostDetailView (post_detail)
我还在 post_detail.html 页面中添加了如下形式的 POST 方法
view.py
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
data = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = data.total_likes()
liked = False
if data.likes.filter(id=self.request.user.id).exists():
liked = True
else:
pass
context["total_likes"] = total_likes
context["liked"] = liked
return context
def LikeView(request,pk):
if request.method == 'POST':
post = get_object_or_404(Post, id=request.POST.get('post_id'))
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
liked = True
post.likes.add(request.user)
return HttpResponseRedirect(reverse('post_detail', args=[str(pk)]))
post_detail.html
{% extends 'blog/base.html' %}
{% block content %}
{% csrf_token %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user_post' object.author.username %}">{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted }}</small>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content|urlize }}</p>
{% if object.author == user %}
<div>
<a class="btn sm btn btn-secondary mb-1" href="{% url 'post_update' object.id %}">Update</a>
<a class="btn sm btn btn-danger mb-1" href="{% url 'post_delete' object.id %}">Delete</a>
</div>
{% endif %}
<br/><br/>
<form action="{% url 'like_post' object.id %}"
method="POST">
{% csrf_token %}
{% if liked %}
<button class="btn btn-danger btn-sm" type="submit", name "post_id", value={{post.id}}>Unlike
</button>
{% else %}
<button class="btn btn-primary btn-sm" type="submit", name "post_id", value={{post.id}}>Like
</button>
{% endif %}
- {{ total_likes }}
</form>
</div>
</article>
{% endblock %}
urls.py
urlpatterns = [
path('', PostListView.as_view(), name='home'),
path('user/<str:username>', UserPostListView.as_view(), name='user_post'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post_detail'),
path('post/<int:pk>/update', PostUpdateView.as_view(), name='post_update'),
path('post/<int:pk>/delete', PostDeleteView.as_view(), name='post_delete'),
path('post/new/', PostCreateView.as_view(), name='post_create'),
path('about/', views.about, name='about'),
path('contact/', views.contactView, name='contact'),
path('success/', views.successView, name='success'),
path('post/<int:pk>/', views.LikeView, name='like_post'),
]
【问题讨论】:
标签: html python-3.x django post