Esempio n. 1
0
 def handle_celery_task_failure(self):
     logger.error("Celery task failure")
     flash_messages = ajax.FlashMessages()
     flash_messages.error(
         _("Something went terribly wrong, please try again shortly."))
     payload = {'messages': flash_messages.to_json(), 'status': 'FAILURE'}
     return HttpResponse(json.dumps(payload), mimetype="application/json")
Esempio n. 2
0
    def formset_invalid(self, formset):
        flash_messages = ajax.FlashMessages()
        flash_messages.warning(_("Your basket couldn't be updated"))

        if self.request.is_ajax():
            ctx = self.get_context_data(formset=formset,
                                        basket=self.request.basket)
            return self.json_response(ctx, flash_messages)

        flash_messages.apply_to_request(self.request)
        return super(BasketView, self).formset_invalid(formset)
Esempio n. 3
0
 def handle_celery_task_result(self, result):
     flash_messages = ajax.FlashMessages()
     msgs = result.pop('flash_messages')
     if result and result.get('methods'):
         self.collect_general_shipping_messages(msgs)
     self.add_flash_messages(flash_messages, msgs)
     return self.shipping_methods_json_response(
         request=self.request,
         ctx=result,
         flash_messages=flash_messages,
         html_template=self.shipping_methods_template_name,
         status='COMPLETED',
         is_valid=True)
Esempio n. 4
0
    def formset_invalid(self, formset):
        flash_messages = ajax.FlashMessages()
        flash_messages.warning(
            _("Your basket couldn't be updated. "
              "Please correct any validation errors below."))

        if self.request.is_ajax():
            ctx = self.get_context_data(formset=formset,
                                        basket=self.request.basket)
            return self.json_response(ctx, flash_messages)

        flash_messages.apply_to_request(self.request)
        return super().formset_invalid(formset)
    def post(self, request, *args, **kwargs):
        if request.is_ajax():
            payload = {}
            flash_messages = ajax.FlashMessages()
            orders_ids = request.POST.getlist('selected_line')
            orders = list(Order.objects.select_related('package').filter(id__in=orders_ids))
            if len(orders):
                payload['download_url'] = self.zip_return_labels(orders)
                flash_messages.success("zip file created successfully")
                self.change_orders_status_to_shipped(orders)
            else:
                flash_messages.info("No orders selected")
            return self.json_response(flash_messages, payload)

        return self.reload_page_response()
Esempio n. 6
0
 def create_response(self):
     """Generate the actual HttpResponse to send back to the user."""
     # if only one result is returned then automatically redirect
     # to that serial category page
     context = self.get_context()
     results = context['serial_results']
     if results.count() == 1:
         cat = results[0]
         return redirect(cat)
     else:
         # if not serials were found, show message to user
         if not results:
             flash_messages = ajax.FlashMessages()
             flash_messages.error(_("No categories were found."))
             flash_messages.apply_to_request(self.request)
         return super(SerialSearchView, self).create_response()
Esempio n. 7
0
    def formset_invalid(self, formset):
        has_deletion = any(formset._should_delete_form(form) for form in formset.forms)
        has_no_invalid_non_deletion = all(form.is_valid() or formset._should_delete_form(form)
                                          for form in formset.forms)
        if has_deletion:
            self.remove_deleted_forms(formset)
            if has_no_invalid_non_deletion:
                return self.formset_valid(formset)

        flash_messages = ajax.FlashMessages()
        flash_messages.warning(_(
            "Your basket has got some issues. "
            "Please correct any validation errors below."))

        if self.request.is_ajax():
            ctx = self.get_context_data(formset=formset,
                                        basket=self.request.basket)
            return self.json_response(ctx, flash_messages)

        flash_messages.apply_to_request(self.request)
        return super().formset_invalid(formset)
Esempio n. 8
0
    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super(AsynBasketAddView, self).form_valid(form)
        flash_messages = ajax.FlashMessages()

        if self.request.is_ajax():
            # Clear django messages from storage since we are using ajax
            storage = messages.get_messages(self.request)
            for message in storage:
                pass
            # push message into message's queue
            flash_messages.info(self.get_success_message(form))

            # pass Basket formset to handle the basket element
            formset = BasketLineFormSet(
                strategy=self.request.basket.strategy,
                queryset=self.request.basket.all_lines())

            ctx = {"formset": formset}
            return self.json_response(ctx, flash_messages)
        else:
            return response
Esempio n. 9
0
    def formset_valid(self, formset):
        # Store offers before any changes are made so we can inform the user of
        # any changes
        offers_before = self.request.basket.applied_offers()
        save_for_later = False

        # Keep a list of messages - we don't immediately call
        # django.contrib.messages as we may be returning an AJAX response in
        # which case we pass the messages back in a JSON payload.
        flash_messages = ajax.FlashMessages()

        for form in formset:
            if (hasattr(form, 'cleaned_data')
                    and form.cleaned_data['save_for_later']):
                line = form.instance
                if self.request.user.is_authenticated():
                    self.move_line_to_saved_basket(line)

                    msg = render_to_string('basket/messages/line_saved.html',
                                           {'line': line})
                    flash_messages.info(msg)

                    save_for_later = True
                else:
                    msg = _("You can't save an item for later if you're "
                            "not logged in!")
                    flash_messages.error(msg)
                    return HttpResponseRedirect(self.get_success_url())

        if save_for_later:
            # No need to call super if we're moving lines to the saved basket
            response = HttpResponseRedirect(self.get_success_url())
        else:
            # Save changes to basket as per normal
            response = super(BasketView, self).formset_valid(formset)

        # If AJAX submission, don't redirect but reload the basket content HTML
        if self.request.is_ajax():
            # Reload basket and apply offers again
            self.request.basket = get_model(
                'basket', 'Basket').objects.get(id=self.request.basket.id)
            self.request.basket.strategy = self.request.strategy
            Applicator().apply(self.request, self.request.basket)
            offers_after = self.request.basket.applied_offers()

            for level, msg in get_messages(self.request.basket,
                                           offers_before,
                                           offers_after,
                                           include_buttons=False):
                flash_messages.add_message(level, msg)

            # Reload formset - we have to remove the POST fields from the
            # kwargs as, if they are left in, the formset won't construct
            # correctly as there will be a state mismatch between the
            # management form and the database.
            kwargs = self.get_formset_kwargs()
            del kwargs['data']
            del kwargs['files']
            if 'queryset' in kwargs:
                del kwargs['queryset']
            formset = self.get_formset()(queryset=self.get_queryset(),
                                         **kwargs)
            ctx = self.get_context_data(formset=formset,
                                        basket=self.request.basket)
            return self.json_response(ctx, flash_messages)

        apply_messages(self.request, offers_before)

        return response
Esempio n. 10
0
    def formset_valid(self, formset):
        # Store offers before any changes are made so we can inform the user of
        # any changes
        # 在进行任何更改之前存储报价,以便我们可以通知用户任何更改。
        offers_before = self.request.basket.applied_offers()
        save_for_later = False

        # Keep a list of messages - we don't immediately call
        # django.contrib.messages as we may be returning an AJAX response in
        # which case we pass the messages back in a JSON payload.
        # 保持一个消息列表-我们不会立即调用django.contrib.messages ,因为我们可能返回
        # 一个Ajax响应,在这种情况下,我们将消息传递回JSON有效载荷。
        flash_messages = ajax.FlashMessages()

        for form in formset:
            if (hasattr(form, 'cleaned_data')
                    and form.cleaned_data['save_for_later']):
                line = form.instance
                if self.request.user.is_authenticated:
                    self.move_line_to_saved_basket(line)

                    msg = render_to_string('basket/messages/line_saved.html',
                                           {'line': line})
                    flash_messages.info(msg)

                    save_for_later = True
                else:
                    msg = _("You can't save an item for later if you're "
                            "not logged in!")
                    flash_messages.error(msg)
                    return redirect(self.get_success_url())

        if save_for_later:
            # No need to call super if we're moving lines to the saved basket
            # 如果我们把行移到保存的购物篮,就不需要调用超级。
            response = redirect(self.get_success_url())
        else:
            # Save changes to basket as per normal
            # 按常规保存购物篮的更改
            response = super().formset_valid(formset)

        # If AJAX submission, don't redirect but reload the basket content HTML
        # 如果Ajax提交,不要重定向,而是重新加载购物篮内容HTML
        if self.request.is_ajax():
            # Reload basket and apply offers again
            # 重新加载购物篮并再次应用报价
            self.request.basket = get_model(
                'basket', 'Basket').objects.get(id=self.request.basket.id)
            self.request.basket.strategy = self.request.strategy
            Applicator().apply(self.request.basket, self.request.user,
                               self.request)
            offers_after = self.request.basket.applied_offers()

            for level, msg in BasketMessageGenerator().get_messages(
                    self.request.basket,
                    offers_before,
                    offers_after,
                    include_buttons=False):
                flash_messages.add_message(level, msg)

            # Reload formset - we have to remove the POST fields from the
            # kwargs as, if they are left in, the formset won't construct
            # correctly as there will be a state mismatch between the
            # management form and the database.
            # 重新加载必须从kwargs as中删除POST字段,如果它们被留在其中,则表单将无法
            # 正确构建,因为管理表单和数据库之间存在状态不匹配。
            kwargs = self.get_formset_kwargs()
            del kwargs['data']
            del kwargs['files']
            if 'queryset' in kwargs:
                del kwargs['queryset']
            formset = self.get_formset()(queryset=self.get_queryset(),
                                         **kwargs)
            ctx = self.get_context_data(formset=formset,
                                        basket=self.request.basket)
            return self.json_response(ctx, flash_messages)

        BasketMessageGenerator().apply_messages(self.request, offers_before)

        return response