我正在创建一个社交媒体网站,用户可以在该网站上互相喜欢。到目前为止,我已经实现了大部分功能,但是我缺少一个重要的部分。
这是在更改按钮内的文本,具体取决于用户是否喜欢该帖子。
“ tuser”变量在Post类上名为“ likes”的多对多字段中查找用户。取决于是否存在。
我将一个变量传递给我的“ home”模板,然后该模板(如果存在)在按钮中显示某些文本。
models.py:
class Post(models.Model):
file = models.ImageField(upload_to='images/')
summary = models.TextField(max_length=600)
pub_date = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.ManyToManyField(User, through='Like', related_name='likes')
def __str__(self):
return self.user.username
def pub_date_pretty(self):
return self.pub_date.strftime('%b %e %Y')
def summary_pretty(self):
return self.summary[:50]
@property
def total_likes(self):
return self.likes.count()
class Like(models.Model):
status = models.BooleanField()
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
views.py
def likepost(request, post_id):
if request.method == 'POST':
post = get_object_or_404(Post, pk=post_id)
user = request.user
if post.likes.filter(id=user.id).exists():
tuser = post.likes.filter(id=user.id)
post.likes.remove(user)
if tuser:
return redirect('home', {'tuser': tuser})
else:
return redirect('home')
else:
like = Like()
like.post = post
like.user = user
like.status = False
like.save()
post.likes.add(user)
return redirect('home')
模板代码:
{% if tuser %}
<a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button></a>
{% else %}
<a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Like {{ post.total_likes }} </button></a>
{% endif %}
<form id="likepost{{ post.id }}" method="POST" action="{% url 'likepost' post.id %}">
{% csrf_token%}
<input type="hidden">
</form>
呈现主页的代码:
@login_required(login_url="/login")
def home(request):
posts = Post.objects.all()
return render(request, 'posts/home.html', {'posts': posts})