我是django的新手,我正在尝试创建一个喜欢的臀部。当我单击按钮时,我可以看到Like模型随用户和用户喜欢的帖子而更新。然后,我还看到Post模型中的总点赞数增加了1。但是它本身的模板仍然显示0个点赞。
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
title = models.CharField(max_length=255)
description = models.CharField(max_length=255)
content = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
categorys = models.ManyToManyField('Category')
tags = models.ManyToManyField('Tag')
likes = models.IntegerField(default=0)
slug = models.SlugField(max_length=100, unique=True)
image = models.ImageField(null=True, upload_to=post_image_file_path)
'''
class Like(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
post = models.ForeignKey('Post', on_delete=models.CASCADE)
created = models.DateTimeField(default=timezone.now)
'''
path('', views.home_view, name='home'),
path('like/', views.like, name='like'),
'''
def home_view(request, *args, **kwargs):
all_posts = services.get_all_posts()
all_categorys = services.get_all_categorys()
all_tags = services.get_all_tags()
context = {'all_posts': all_posts, 'all_categorys': all_categorys,
'all_tags': all_tags}
return render(request, 'blog/home.html', context)
def like(request, *args, **kwargs):
if request.method == 'GET':
model = get_user_model()
postid = request.GET.get('postid')
user = model.objects.get(id=request.user.id)
post = Post.objects.get(id=postid)
if Like.objects.filter(user=user, post=post).exists():
Like.objects.filter(user=user, post=post).delete()
update_likes = Post.objects.get(id=post.id)
update_likes.likes -= 1 # change field
update_likes.save() # this will update only
else:
like = Like.objects.create(user=user, post=post)
update_likes = Post.objects.get(id=post.id)
update_likes.likes += 1 # change field
update_likes.save() # this will update only
return redirect('blog:home')
'''
{% for post in all_posts %}
html...
<form action="{% url 'blog:like'%}" method="GET">
<input type="hidden" name="postid" value="{{ post.id }}">
<button type="submit" class="btn btn-success">Like</button>
</form>
<p>total = {{ post.likes }}</p>
{% endfor %}
'''
我确定这不是最好的方法,但是我想理解为什么重定向到主视图后,模板没有用新值更新。
答案 0 :(得分:0)
You need to use ajax for the automate template update, otherwise you'll have to refresh each time
Also add the never_cache decorator
在您的views.py文件中查看
from django.views.decorators.cache import never_cache
@never_cache
def yourView(...):
....
或者如果您有基于类的视图
from django.views.decorators.cache import never_cache
class YourView(View):
@never_cache
def dispatch(self,request,*args,**kwargs):
return super().dispatch(request,*args,**kwargs)