简体   繁体   English

如何基于查询集过滤器显示 django 消息?

[英]How to show django messages based on queryset filter?

I want to show message based on my filter.我想根据我的过滤器显示消息。

CHOICES = (

        ('0', 'published',),

        ('1', 'pending',),

        ('2', 'rejected',),

        )

Here I tried this code for showing message based on filter but it's only showing the published message.在这里,我尝试使用此代码基于过滤器显示消息,但它仅显示已发布的消息。

def get_context_data(self, **kwargs):

            data = super().get_context_data(**kwargs)

            published = BlogComment.objects.filter(is_published="0")

            pending = BlogComment.objects.filter(is_published="1")

            

            if published:

                 messages.add_message(self.request, messages.INFO, 'Comment status published Sucessfully')

            elif pending: 

               messages.add_message(self.request, messages.INFO, 'Comment status pending Sucessfully')

            

            return data

why I am only getting the published message?为什么我只收到已发布的消息?

I also tried if statement instead of elif.我也尝试了 if 语句而不是 elif。 After using if statement I am getting three message at time while changing status of any object.使用 if 语句后,我在更改任何 object 的状态时一次收到三条消息。

        if published:
             messages.add_message(self.request, messages.INFO, 'Comment Published Sucessfully')
        if pending: 
             messages.add_message(self.request, messages.INFO, 'Comment Status Pending')
        if rejected:
             messages.add_message(self.request, messages.INFO, 'Comment Status 

Are you trying to display the status update of a single object?您是否尝试显示单个 object 的状态更新? If so then you can simply update your view logic where view is inherited from from django.views.generic import UpdateView .如果是这样,那么您可以简单地更新您的视图逻辑,其中视图是from django.views.generic import UpdateView继承的。

from django.views.generic import UpdateView
from django.contrib import messages


class YourUpdateView(UpdateView):
    # other part of view 
   
    def form_valid(self, form):
        self.object = form.save()
        status = self.object.status
        messages.success(self.request, f"Status updated to {status}")
        return super().form_valid(form)

If I'm mistaken please explain in detail in the comment.如果我弄错了,请在评论中详细解释。

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

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