简体   繁体   中英

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. After using if statement I am getting three message at time while changing status of any 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? 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.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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