简体   繁体   English

如何更改 django 中点赞按钮的颜色?

[英]How can I change the color on the like button in django?

I did create (like and dislike) in my project and I need it when someone clicks on the button.我确实在我的项目中创建(喜欢和不喜欢),当有人点击按钮时我需要它。 the color will change to blue颜色将变为蓝色
I saw something like that where I could create a variable called something like: is_liked = False, and I can place that in HTML by context to trigger it in (if condition) but it's not working with me so, How can I run the color on the like button?我看到了类似的东西,我可以创建一个名为 is_liked = False 的变量,我可以通过上下文将它放在 HTML 中以触发它(如果条件),但它不适用于我,我该如何运行颜色在喜欢按钮上?

views.py视图.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模型.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())

how can I put the condition in the HTML page to check if is_liked is True or False?如何将条件放在 HTML 页面中以检查 is_liked 是真还是假?

In Django Html use template like this在 Django Html 使用这样的模板

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

I had to add a condition to get_context where that way did work with me.我必须向 get_context 添加一个条件,这种方式对我有用。 this way I didn't see before but it works perfectly:这种方式我以前没有见过,但效果很好:

views.py视图.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())

at this moment, I add a condition on the view I already handle as you see above in the QuestionDetail model.此刻,我在已处理的视图上添加了一个条件,正如您在上面的 QuestionDetail model 中看到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM