Как изменить цвет кнопки лайка в django? - PullRequest
0 голосов
/ 09 июля 2020

Я создал (нравится и не нравится) в моем проекте, и мне это нужно, когда кто-то нажимает на кнопку. цвет изменится на синий
Я видел что-то подобное, где я мог создать переменную с названием что-то вроде: is_liked = False, и я могу поместить это в HTML по контексту, чтобы вызвать ее (если условие), но это не работает со мной так, как я могу запустить цвет на кнопке Like?

views.py

# Detail question and Create comment
class QuestionDetail(DetailView, SingleObjectMixin):
    template_name = 'community/question_view.html'
    slug_field = 'ask_slug'
    slug_url_kwarg = 'user_slug'
    model = UserAsking
    queryset = UserAsking.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['my_question'] = UserAsking.objects.get(title=self.object)
        self_post = UserAsking.objects.get(title=self.object)
        post_slug = UserAsking.objects.get(ask_slug=self_post.ask_slug)
        context['summation'] = post_slug.likes.count() - post_slug.dislikes.count()
        context['comment_form'] = CommentForm
        comments_count = Comment.objects.filter(userasking=UserAsking.objects.get(title=self.object))
        context['comments_count'] = comments_count.count()
        # liked_post = User.objects.get(username=self.request.user.username).likes.exists()
        # context['liked_post'] = liked_post
        # disliked_post = User.objects.get(username=self.request.user.username).dislikes.exists()
        # context['disliked_post'] = disliked_post
        return context

    def post(self, request, user_slug, *args, **kwargs):
        my_question = UserAsking.objects.get(ask_slug=user_slug)
        userprof = UserProfile.objects.get(userasking__ask_slug=user_slug)
        comment_form = CommentForm(request.POST, instance=request.user)
        name = "%s %s" % (self.request.user.first_name, self.request.user.last_name)
        username = self.request.user.username
        logo = self.request.user.userprofile.logo.url
        c = CommentForm(self.request.POST).add_error('comment', 'error')
        if comment_form.is_valid():
            comment_form = Comment.objects.create(comment=self.request.POST.get('comment', None),
                                                  userasking_id=my_question.id,
                                                  userprofile_id=userprof.id,
                                                  name=name,
                                                  username=username,
                                                  logo=logo,
                                                  comment_slug=my_question.ask_slug
                                                  )
            comment_form.save()
            return redirect('community:question_view', comment_form.userasking.ask_slug)
        return render(request, 'community/question_view.html', {'comment_form': comment_form,
                                                                'c': c})
# Like post function
class LikePost(View, SingleObjectMixin):
    template_name = 'community/question_view.html'

    def post(self, request, *args, **kwargs):
        post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_slug'))
        if post.dislikes.filter(username=request.user).exists():
            post.dislikes.remove(request.user)
            post.likes.add(request.user)

models.py

class UserAsking(models.Model):
    userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
    question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
    field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')
    date = models.DateTimeField(auto_now_add=True)
    ask_slug = models.SlugField(max_length=100)
    likes = models.ManyToManyField(User, related_name='likes', blank=True)
    dislikes = models.ManyToManyField(User, related_name='dislikes', blank=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('community:question_view', kwargs={'user_slug': self.ask_slug})

    def save(self, *args, **kwargs):
        self.ask_slug = slugify(self.title)
        super().save(*args, **kwargs)
            elif post.likes.filter(username=request.user).exists():
                post.likes.remove(request.user)
            else:
                post.likes.add(request.user)
            return redirect(post.get_absolute_url())
    
    
    # Dislike post function
    class DisLikePost(View, SingleObjectMixin):
    
        def post(self, request, *args, **kwargs):
            post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_dislike_slug'))
            if post.likes.filter(username=request.user).exists():
                post.likes.remove(request.user)
                post.dislikes.add(request.user)
            elif post.dislikes.filter(username=request.user).exists():
                post.dislikes.remove(request.user)
            else:
                post.dislikes.add(request.user)
            return redirect(post.get_absolute_url())

как я могу поставить условие на странице HTML, чтобы проверить, является ли is_liked истинным или ложным?

Ответы [ 2 ]

0 голосов
/ 09 июля 2020

Мне пришлось добавить условие в get_context, где этот способ работал со мной. таким способом я раньше не видел, но он отлично работает:

views.py

class QuestionDetail(DetailView, SingleObjectMixin):
    template_name = 'community/question_view.html'
    slug_field = 'ask_slug'
    slug_url_kwarg = 'user_slug'
    model = UserAsking
    queryset = UserAsking.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['my_question'] = UserAsking.objects.get(title=self.object)
        self_post = UserAsking.objects.get(title=self.object)
        post_slug = UserAsking.objects.get(ask_slug=self_post.ask_slug)
        context['summation'] = post_slug.likes.count() - post_slug.dislikes.count()
        context['comment_form'] = CommentForm
        comments_count = Comment.objects.filter(userasking=UserAsking.objects.get(title=self.object))
        context['comments_count'] = comments_count.count()
        context['is_liked'] = False
        context['is_dislike'] = False
        # context to like the post
        if LikePost.as_view():
            if post_slug.dislikes.filter(username=self.request.user).exists():
                context['is_liked'] = False
            elif post_slug.likes.filter(username=self.request.user).exists():
                context['is_liked'] = True
            else:
                context['is_liked'] = False
        # context to dis-like the post
        if DisLikePost.as_view():
            if post_slug.likes.filter(username=self.request.user).exists():
                context['is_dislike'] = False
            elif post_slug.dislikes.filter(username=self.request.user).exists():
                context['is_dislike'] = True
            else:
                context['is_dislike'] = False
        return context

    def post(self, request, user_slug, *args, **kwargs):
        my_question = UserAsking.objects.get(ask_slug=user_slug)
        userprof = UserProfile.objects.get(userasking__ask_slug=user_slug)
        comment_form = CommentForm(request.POST, instance=request.user)
        name = "%s %s" % (self.request.user.first_name, self.request.user.last_name)
        username = self.request.user.username
        logo = self.request.user.userprofile.logo.url
        c = CommentForm(self.request.POST).add_error('comment', 'error')
        if comment_form.is_valid():
            comment_form = Comment.objects.create(comment=self.request.POST.get('comment', None),
                                                  userasking_id=my_question.id,
                                                  userprofile_id=userprof.id,
                                                  name=name,
                                                  username=username,
                                                  logo=logo,
                                                  comment_slug=my_question.ask_slug
                                                  )
            comment_form.save()
            return redirect('community:question_view', comment_form.userasking.ask_slug)
        return render(request, 'community/question_view.html', {'comment_form': comment_form,
                                                                'c': c})
# Like post function
class LikePost(View, SingleObjectMixin):
    template_name = 'community/question_view.html'

    def post(self, request, *args, **kwargs):
        post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_slug'))
        if post.dislikes.filter(username=request.user).exists():
            post.dislikes.remove(request.user)
            post.likes.add(request.user)
        elif post.likes.filter(username=request.user).exists():
            post.likes.remove(request.user)
        else:
            post.likes.add(request.user)
        return redirect(post.get_absolute_url())


# Dislike post function
class DisLikePost(View, SingleObjectMixin):

    def post(self, request, *args, **kwargs):
        post = get_object_or_404(UserAsking, ask_slug=request.POST.get('post_dislike_slug'))
        if post.likes.filter(username=request.user).exists():
            post.likes.remove(request.user)
            post.dislikes.add(request.user)
        elif post.dislikes.filter(username=request.user).exists():
            post.dislikes.remove(request.user)
        else:
            post.dislikes.add(request.user)
        return redirect(post.get_absolute_url())

в этот момент я добавляю условие для представления, которое я уже обрабатываю, как вы см. выше в модели QuestionDetail.

0 голосов
/ 09 июля 2020

В Django Html используйте такой шаблон

{% if query_set.is_like %}
...do something
 change back color like <h1 style:background:''blue></h1>
{% else %}
No change... <h1></h1>
{% endif%}
...