Django:消息未显示

时间:2017-10-08 03:41:33

标签: django django-messages

我在ListView中对所选行的批量操作有以下功能。 我正在显示成功和错误的消息。

def archive_stores(view, queryset):
    if queryset.exists():
        queryset.update(archive=True)
        success_message = messages.success(view.request, 'Archived successfully.')
        return HttpResponseRedirect(reverse('stores_list', success_message))
    else: #The message is not shown when queryset of empty.
        error_message = messages.error(view.request, 'No success!.')
        return HttpResponseRedirect(reverse_lazy('stores_list', error_message))

正确显示成功消息。但错误消息永远不会出现。请指导我可能是什么原因?

以下是ListView:

@method_decorator(login_required, name='dispatch')
class StoresListView(ActionViewMixin,ListFilteredMixin,ListView):
    template_name = 'stores_listing.html'
    model = Store
    filter_set = StoreFilter
    actions = [archive_stores, unarchive_stores, delete_stores, export_stores,]
    paginate_by = 25

以下是消息模板:

{% for message in messages %}
  <div class="alert {{ message.tags }} alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
    {{ message | safe }}
  </div>
{% endfor %}

感谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

   def archive_stores(view, queryset):
      if queryset:
        queryset.update(archive=True)
        success_message = messages.success(view.request, 'Archived successfully.')
        return  HttpResponseRedirect(reverse('stores_list', success_message))
      else: #The message is not shown when queryset of empty.
         error_message = messages.error(view.request, 'No success!.')
         return HttpResponseRedirect(reverse_lazy('stores_list', error_message))

我认为您不必将消息显式传递为kwarg,因为单独调用message.success()或message.error()将包含所需的消息。您可以像这样更新您的视图:

   def archive_stores(view, queryset):
      if queryset:
        queryset.update(archive=True)
        messages.success(view.request, 'Archived successfully.')
        return  HttpResponseRedirect(reverse('stores_list'))
      else: #The message is not shown when queryset of empty.
         messages.error(view.request, 'No success!.')
         return HttpResponseRedirect(reverse_lazy('stores_list'))