Example #1
0
    def dispatch(self, request, *args, **kwargs):
        module_str = "%s:%s" % (request.GET.get("module"), request.GET.get("model"))
        self.return_url = reverse("shuup_admin:%s.list" % request.GET.get("return_url"))
        match = resolve(self.return_url)
        view_context = load("%s:%s" % (match.func.__module__, match.func.__name__))

        default_columns = view_context.default_columns
        self.model = load(module_str)
        self.settings = ViewSettings(self.model, default_columns, view_context)
        return super(ListSettingsView, self).dispatch(request, *args, **kwargs)
Example #2
0
    def __init__(self):
        super(PicotableListView, self).__init__()
        if self.mass_actions:
            self.default_columns = [
                Column("select",
                       "",
                       display="",
                       sortable=False,
                       linked=False,
                       class_name="text-center"),
            ] + self.default_columns

        self.settings = ViewSettings(self.model,
                                     self.default_columns,
                                     view_context=self)

        if self.mass_actions:
            if self.settings.columns:
                # settings.columns never have selects
                self.columns = [
                    Column("select",
                           "",
                           display="",
                           sortable=False,
                           linked=False,
                           class_name="text-center"),
                ] + self.settings.columns
            else:
                self.columns = self.default_columns
        else:
            self.columns = (self.settings.columns or self.default_columns)
Example #3
0
 def process(self, request, ids):
     shop = get_shop(request)
     if isinstance(ids, string_types) and ids == "all":
         query = Q(shop=shop)
     else:
         query = Q(product__pk__in=ids, shop=shop)
     view_settings = ViewSettings(ShopProduct,
                                  ProductListView.default_columns,
                                  ProductListView)
     response = HttpResponse(content_type='text/csv')
     response['Content-Disposition'] = 'attachment; filename="products.csv"'
     writer = csv.writer(response, delimiter=";", encoding='utf-8')
     writer.writerow([col.title for col in view_settings.columns])
     for shop_product in ShopProduct.objects.filter(query):
         row = []
         for dr in [col.id for col in view_settings.columns]:
             if dr.startswith("shopproduct_"):
                 row.append(
                     getattr(shop_product, dr.replace("shopproduct_", "")))
             elif dr.startswith("product_"):
                 row.append(
                     getattr(shop_product.product,
                             dr.replace("product_", "")))
             else:
                 row.append(getattr(shop_product.product, dr))
         writer.writerow(row)
     return response
Example #4
0
def test_export_customer_sample(rf):
    # create input: shop, request to use in process(request, ids) method
    base_view = ExportContactsCSVAction()
    random_customer = create_random_person()

    request = apply_request_middleware(rf.get("/"),
                                       user=get_default_staff_user())
    view_instance = ContactListView()
    view_instance.request = request
    view_settings = ViewSettings(Contact, ContactListView.default_columns,
                                 view_instance)
    setting_cols = view_settings.columns

    customer_from_query = base_view.get_queryset(request, view_instance,
                                                 [random_customer.pk])[0]
    assert customer_from_query.pk == random_customer.pk

    response = base_view.process(request, [random_customer.pk])
    assert response.status_code == 200

    content = response.content.decode("utf-8")
    cvs_reader = csv.reader(io.StringIO(content))
    body = list(cvs_reader)
    headers = body.pop(0)
    for dr in setting_cols:
        index = setting_cols.index(dr)
        assert (strip_tags(
            dr.get_display_value(
                view_settings.view_context,
                random_customer))) == body[0][0].split(";")[index]

    assert len(view_settings.columns) == len(headers[0].split(";"))
Example #5
0
    def process(self, request, ids):
        view_instance = self.view_class()
        view_instance.request = request
        view_settings = ViewSettings(self.model,
                                     self.view_class.default_columns,
                                     view_instance)
        queryset = self.get_queryset(request, view_instance, ids)

        response = HttpResponse(content_type="text/csv")
        response[
            "Content-Disposition"] = f'attachment; filename="{self.filename}"'
        writer = csv.writer(response, delimiter=";", encoding="utf-8")
        writer.writerow([col.title for col in view_settings.columns])

        for item in queryset:
            row = []
            for dr in view_settings.columns:
                if dr.get_display_value(view_settings.view_context, item):
                    row.append(
                        strip_tags(
                            dr.get_display_value(view_settings.view_context,
                                                 item)))
                else:
                    row.append(None)
            writer.writerow(row)

        return response
Example #6
0
def test_provide_columns():
    with override_provides(
            "provided_columns_ShopProduct",
        ["shuup_tests.admin.test_picotable:CustomProductDataColumn"]):
        view_settings = ViewSettings(ShopProduct,
                                     ProductListView.default_columns,
                                     ProductListView)
        column_ids = [col.id for col in view_settings.inactive_columns
                      ]  # provided column is not set active yet
        assert "custom_product_info" in column_ids
Example #7
0
class ListSettingsView(FormView):
    form_class = ColumnSettingsForm
    template_name = "shuup/admin/edit_settings.jinja"

    def dispatch(self, request, *args, **kwargs):
        module_str = "%s:%s" % (request.GET.get("module"),
                                request.GET.get("model"))
        self.return_url = reverse("shuup_admin:%s.list" %
                                  request.GET.get("return_url"))
        match = resolve(self.return_url)
        view_context = load("%s:%s" %
                            (match.func.__module__, match.func.__name__))

        default_columns = view_context.default_columns
        self.model = load(module_str)
        self.settings = ViewSettings(self.model, default_columns, view_context)
        return super(ListSettingsView, self).dispatch(request, *args, **kwargs)

    def get_form(self, form_class=None):
        kwargs = self.get_form_kwargs()
        return ColumnSettingsForm(self.settings, **kwargs)

    def get_initial(self):
        initial = super(ListSettingsView, self).get_initial()
        for col in self.settings.columns:
            key = self.settings.get_settings_key(col.id)
            initial.update({key: self.settings.get_config(col.id)})
        return initial

    def form_valid(self, form):
        ordered_columns = self.request.POST.get("ordering", "").split("|")
        for idx, ordered_col in enumerate(ordered_columns):
            col_data = {"ordering": idx, "active": True}
            self.settings.set_config(ordered_col, col_data, use_key=True)

        for col, val in six.iteritems(form.cleaned_data):
            if col in ordered_columns:
                continue
            col_data = {"ordering": 99999, "active": False}
            self.settings.set_config(col, col_data, use_key=True)

        messages.success(self.request,
                         _("Settings saved."),
                         fail_silently=True)
        return HttpResponseRedirect(self.return_url)

    def get_context_data(self, **kwargs):
        context = super(ListSettingsView, self).get_context_data(**kwargs)
        context["toolbar"] = Toolbar([
            PostActionButton(
                icon="fa fa-save",
                form_id="settings_form",
                text=_("Save"),
                extra_css_class="btn-success",
            ),
            JavaScriptActionButton(
                icon="fa fa-cog",
                text=_("Reset Defaults"),
                onclick="resetDefaultValues()",
            )
        ],
                                     view=self)
        context["defaults"] = "|".join([
            self.settings.get_settings_key(c.id)
            for c in self.settings.default_columns
        ])
        return context
Example #8
0
class ListSettingsView(FormView):
    form_class = ColumnSettingsForm
    template_name = "shuup/admin/edit_settings.jinja"

    def dispatch(self, request, *args, **kwargs):
        module_str = "%s:%s" % (request.GET.get("module"), request.GET.get("model"))
        self.return_url = reverse("shuup_admin:%s.list" % request.GET.get("return_url"))
        match = resolve(self.return_url)
        view_context = load("%s:%s" % (match.func.__module__, match.func.__name__))

        default_columns = view_context.default_columns
        self.model = load(module_str)
        self.settings = ViewSettings(self.model, default_columns, view_context)
        return super(ListSettingsView, self).dispatch(request, *args, **kwargs)

    def get_form(self, form_class=None):
        kwargs = self.get_form_kwargs()
        return ColumnSettingsForm(self.settings, **kwargs)

    def get_initial(self):
        initial = super(ListSettingsView, self).get_initial()
        for col in self.settings.columns:
            key = self.settings.get_settings_key(col.id)
            initial.update({
                key: self.settings.get_config(col.id)
            })
        return initial

    def form_valid(self, form):
        ordered_columns = self.request.POST.get("ordering", "").split("|")
        for idx, ordered_col in enumerate(ordered_columns):
            col_data = {
                "ordering": idx,
                "active": True
            }
            self.settings.set_config(ordered_col, col_data, use_key=True)

        for col, val in six.iteritems(form.cleaned_data):
            if col in ordered_columns:
                continue
            col_data = {
                "ordering": 99999,
                "active": False
            }
            self.settings.set_config(col, col_data, use_key=True)

        messages.success(self.request, _("Settings saved"), fail_silently=True)
        return HttpResponseRedirect(self.return_url)

    def get_context_data(self, **kwargs):
        context = super(ListSettingsView, self).get_context_data(**kwargs)
        context["toolbar"] = Toolbar([
            PostActionButton(
                icon="fa fa-save",
                form_id="settings_form",
                text=_("Save"),
                extra_css_class="btn-success",
            ),
            JavaScriptActionButton(
                icon="fa fa-cog",
                text=_("Reset Defaults"),
                onclick="resetDefaultValues()",
            )
        ], view=self)
        context["defaults"] = "|".join([self.settings.get_settings_key(c.id) for c in self.settings.default_columns])
        return context