无法 return 在详细信息视图中写入上下文
can't return write context in Detail View
**post_detail.html**
{{post.total_likes}}
<form class="" action="{%url 'like_post' %}" method="post">
{%csrf_token%}
{% if is_liked %}
<button type="submit" value="{{post.id}}" name="post_id" class="btn btn-danger">DisLike</button>
{% else %}
<button type="submit" value="{{post.id}}" name="post_id" class="btn btn-primary">Like</button>
{% endif %}
</form>
**views.py**
def like_post(request):
post = get_object_or_404(Post,id=request.POST.get('post_id'))
is_liked=False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
is_liked=False
else:
post.likes.add(request.user)
is_liked=True
return HttpResponseRedirect(post.get_absolute_url())
class PostDetailView(DetailView):
model = Post
fields = ['likes']
def get_context_data(self,**kwargs):
post = self.get_object()
request = self.request
post.is_liked = False
if post.likes.filter(id=request.user.id).exists():
post.is_liked = True
context = super().get_context_data(**kwargs)
context['total_likes','is_liked'] = [post.total_likes(),post.is_liked]
return context
**urls.py**
from django.urls import path
from django.conf.urls import url
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
SearchResultView
)
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='Blog-home'),
path('search/', SearchResultView.as_view(), name='search-result'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('about/', views.about, name='Blog-about'),
path('like/',views.like_post,name="like_post"),
]
**models.py**
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
ikes = models.ManyToManyField(User,related_name='likes',blank=True)
def __str__(self):
return self.title
def total_likes(self):
return self.likes.count()
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
这是我的代码。它没有任何错误,唯一的问题是点赞按钮保持不变,即点赞似乎总是错误的。我为 post_detail 使用了基于 class 的视图,并将 get_context_data 方法添加到 it.But 我认为这种方法不起作用。所以我需要为 PostDetailView.Rest 编写代码,一切正常 fine.Main PostDetailView 中的问题正在返回 is_liked 始终为 false。
我应该改用功能视图吗?
问题出在这里:
context['total_likes','is_liked'] = [post.total_likes(),post.is_liked]
实际上是生成这样一个字典:
{('total_likes', 'is_liked'): [100, True]}
而是像这样更新上下文:
context.update({'total_likes': post.total_likes(), 'is_liked': post.is_liked})
return context
**post_detail.html**
{{post.total_likes}}
<form class="" action="{%url 'like_post' %}" method="post">
{%csrf_token%}
{% if is_liked %}
<button type="submit" value="{{post.id}}" name="post_id" class="btn btn-danger">DisLike</button>
{% else %}
<button type="submit" value="{{post.id}}" name="post_id" class="btn btn-primary">Like</button>
{% endif %}
</form>
**views.py**
def like_post(request):
post = get_object_or_404(Post,id=request.POST.get('post_id'))
is_liked=False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
is_liked=False
else:
post.likes.add(request.user)
is_liked=True
return HttpResponseRedirect(post.get_absolute_url())
class PostDetailView(DetailView):
model = Post
fields = ['likes']
def get_context_data(self,**kwargs):
post = self.get_object()
request = self.request
post.is_liked = False
if post.likes.filter(id=request.user.id).exists():
post.is_liked = True
context = super().get_context_data(**kwargs)
context['total_likes','is_liked'] = [post.total_likes(),post.is_liked]
return context
**urls.py**
from django.urls import path
from django.conf.urls import url
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
SearchResultView
)
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='Blog-home'),
path('search/', SearchResultView.as_view(), name='search-result'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('about/', views.about, name='Blog-about'),
path('like/',views.like_post,name="like_post"),
]
**models.py**
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
ikes = models.ManyToManyField(User,related_name='likes',blank=True)
def __str__(self):
return self.title
def total_likes(self):
return self.likes.count()
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
这是我的代码。它没有任何错误,唯一的问题是点赞按钮保持不变,即点赞似乎总是错误的。我为 post_detail 使用了基于 class 的视图,并将 get_context_data 方法添加到 it.But 我认为这种方法不起作用。所以我需要为 PostDetailView.Rest 编写代码,一切正常 fine.Main PostDetailView 中的问题正在返回 is_liked 始终为 false。
我应该改用功能视图吗?
问题出在这里:
context['total_likes','is_liked'] = [post.total_likes(),post.is_liked]
实际上是生成这样一个字典:
{('total_likes', 'is_liked'): [100, True]}
而是像这样更新上下文:
context.update({'total_likes': post.total_likes(), 'is_liked': post.is_liked})
return context