Я пытаюсь разработать кнопку «Мне нравится» для публикации на домашней странице. Модель профиля находится в соотношении один к одному с моделью пользователя. Модели:
class Profile(models.Model):
Follwers=models.IntegerField(default='0')
user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True)
bio=models.TextField(max_length=120,blank=True)
location=models.CharField(max_length=30,blank=True)
birth_date=models.DateField(null=True,blank=True)
verified=models.BooleanField(default=False)
ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True,default='UserAvatar/ProfileFilled.svg')
def __str__(self):
return self.user.username
@receiver(post_save,sender=User)
def update_user_profile(sender,instance,created,**kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
class post(models.Model):
Profile=models.ForeignKey(Profile,on_delete=models.CASCADE)
Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True)
DatePosted=models.DateTimeField(default=timezone.now)
Content=models.TextField(blank=True,null=True)
def __str__(self):
return self.Profile.user.username
class Meta:
ordering=['-DatePosted']
@property
def like_count(self):
return len(likes.objects.filter(post=self))
class likes(models.Model):
Profile=models.ForeignKey(Profile,on_delete=models.CASCADE)
post=models.ForeignKey(post,on_delete=models.CASCADE)
URL для ajax:
urlpatterns=[
path('ajax/check_like',views.check_like,name='check_like'),]
соответствующая функция просмотра -
def check_like(request):
if request.user.is_authenticated:
if request.method == 'POST':
form = LikeForm(request.POST)
if form.is_valid():
postid_id=request.POST['post']
checking=likes.objects.get(post__id=postid_id,Profile__user=request.user)
if checking:
checking.delete()
U=1
return JsonResponse(U)
else:
create=likes.objects.create(post__id=postid_id,Profile__user=request.user)
V=0
return JsonResponse(V)
else:
redirect('signup')
, в то время как шаблон -
{% if result %}
<div class="infinite-container">
{% for p in result %}
<div class="infinite-item">
<div class="PostHeader">
{% if p.Profile.ProfilePic %}<img src="{{ p.Profile.ProfilePic.url}}"/>
{% else %}<img src="{%static "images/icons/ProfileFilled.svg" %}"/>{% endif%}
<a href="/Profile/{{ p.Profile.user.username }}">{{ p.Profile.user.username }}</a>
</div>
{% if p.Picture %}<div class="ImageContainer"><img src="{{p.Picture.url}}"/></div>{% endif %}
{% if p.Content %}<div class="Content"><p> {{ p.Content }}</p></div>{% endif %}
<form id="like_form">
{% csrf_token %}
<input type="hidden" name="post" id="post_id"value="{{ post.id }}">
<button id="likesubmit" type="submit"></button></form>
<div class="SpriteContainer">
<label for="likesubmit">
{% if U %}
<div class='Heart' style="color:#000000;">♡</div><!-- ♥ for filled heart ♡ for empty heart--></div>
{% endif %}
{% if V %}
<div class="Heart">♡</div>
{% endif %}
</label>
<div class="CommentBody">
{% for comm in p.comment_set.all %}
<div class="CommentRow"><a href="Profile/{{ comm.Profile.user.username }}"style="color:#000;font-weight:bold;font-size: 15px">{{ comm.Profile.user.username }}</a> {{ comm.Content }}
</div>
{% endfor %}
</div>
</div>
{% endfor %}
, а код ajax выглядит следующим образом:
<script>
$(document).on('submit','#like_form',function (e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'/ajax/check_like',
data:{
post:$('#post_id').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function (response) {
console.log("liked");
}
});
});
Я хочу, чтобы кнопка «Мне нравится» меняла свой цвет в зависимости от того, понравился он мне или не понравился. Что я делаю не так?