def test_model_url(): with admin_only_urls(): with pytest.raises(NoModelUrl): get_model_url(Counter) # That's silly! p = Product() p.pk = 3 assert get_model_url(p)
def _get_parent_and_sibling_items(self, parent, siblings): yield DropdownItem( text=_("Parent: %s") % parent, icon="fa fa-eye", url=get_model_url(parent), ) for sib in siblings: yield DropdownItem( text=_("Sibling: %s") % sib, icon="fa fa-eye", url=get_model_url(sib), )
def _get_children_items(self, children): for child in children: yield DropdownItem( text=_("Child: %s") % child, icon="fa fa-eye", url=get_model_url(child), )
def get_toolbar(self): toolbar = get_default_edit_toolbar(self, "change_password_form", discard_url=get_model_url( self.object), with_split_save=False) return toolbar
def form_valid(self, form): product_ids_to_quantities = dict( (int(key.replace("q_", "")), value) for (key, value) in six.iteritems(form.cleaned_data) if key.startswith("q_") and value > 0 ) order = self.object product_map = Product.objects.in_bulk(set(product_ids_to_quantities.keys())) products_to_quantities = dict( (product_map[product_id], quantity) for (product_id, quantity) in six.iteritems(product_ids_to_quantities) ) try: shipment = order.create_shipment( supplier=form.cleaned_data["supplier"], product_quantities=products_to_quantities ) except NoProductsToShipException: messages.error(self.request, _("No products to ship.")) return self.form_invalid(form) else: messages.success(self.request, _("Shipment %s created.") % shipment.id) return HttpResponseRedirect(get_model_url(order))
def get_breadcrumb_parents(self): return [ MenuEntry( text=self.object, url=get_model_url(self.object) ) ]
def get_breadcrumb_parents(self): return [ MenuEntry( text="%s" % self.object, url=get_model_url(self.object) ) ]
def get_toolbar(self): toolbar = get_default_edit_toolbar(self, "permissions_form", discard_url=get_model_url( self.object), with_split_save=False) return toolbar
def form_valid(self, form): product_ids_to_quantities = dict( (int(key.replace("q_", "")), value) for (key, value) in six.iteritems(form.cleaned_data) if key.startswith("q_") and value > 0) order = self.object product_map = Product.objects.in_bulk( set(product_ids_to_quantities.keys())) products_to_quantities = dict( (product_map[product_id], quantity) for (product_id, quantity) in six.iteritems(product_ids_to_quantities)) unsaved_shipment = Shipment(order=order, supplier=form.cleaned_data["supplier"]) for extend_class in get_provide_objects(FORM_MODIFIER_PROVIDER_KEY): extend_class().form_valid_hook(form, unsaved_shipment) try: shipment = order.create_shipment( product_quantities=products_to_quantities, shipment=unsaved_shipment) except NoProductsToShipException: messages.error(self.request, _("No products to ship.")) return self.form_invalid(form) else: messages.success(self.request, _("Shipment %s created.") % shipment.id) return HttpResponseRedirect(get_model_url(order))
def get_toolbar(self): toolbar = get_default_edit_toolbar( self, "permissions_form", discard_url=get_model_url(self.object), with_split_save=False ) return toolbar
def check_for_delete(view, request, object): can_delete = object.can_delete() delete_url = get_model_url(object, "delete") response = view(request, pk=object.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] assert bool(delete_url in force_text(response.content)) == can_delete
def get_toolbar(self): toolbar = get_default_edit_toolbar( self, "change_password_form", discard_url=get_model_url(self.object), with_split_save=False ) return toolbar
def get_toolbar(self): save_form_id = self.get_save_form_id() object = self.get_object() delete_url = get_model_url(object, "delete") if object.pk else None return get_default_edit_toolbar( self, save_form_id, delete_url=(delete_url if object.can_delete() else None))
def get_toolbar(self): toolbar = get_default_edit_toolbar( self, self.get_save_form_id(), discard_url=(get_model_url(self.object) if self.object.pk else None)) # TODO: Add extensibility return toolbar
def get_toolbar(self): toolbar = get_default_edit_toolbar( self, self.get_save_form_id(), discard_url=(get_model_url(self.object) if self.object.pk else None) ) # TODO: Add extensibility return toolbar
def get_toolbar(self): try: new_url = get_model_url(self.model, kind="new") except NoModelUrl: new_url = None if new_url: return Toolbar([NewActionButton(new_url)])
def get_search_results(self, request, query): minimum_query_length = 3 if len(query) >= minimum_query_length: users = get_user_model().objects.filter(Q(username__icontains=query) | Q(email=query)) for i, user in enumerate(users[:10]): relevance = 100 - i yield SearchResult( text=six.text_type(user), url=get_model_url(user), category=self.category, relevance=relevance )
def get_search_results(self, request, query): minimum_query_length = 3 if len(query) >= minimum_query_length: contacts = Contact.objects.filter( Q(name__icontains=query) | Q(email=query)) for i, contact in enumerate(contacts[:10]): relevance = 100 - i yield SearchResult(text=six.text_type(contact), url=get_model_url(contact), category=self.category, relevance=relevance)
def test_product_module_search(rf, admin_user): get_default_shop() request = apply_request_middleware(rf.get("/"), user=admin_user) with replace_modules([ProductModule]): with admin_only_urls(): default_product = get_default_product() model_url = get_model_url(default_product) sku = default_product.sku assert any(sr.url == model_url for sr in get_search_results(request, query=sku)) # Queries work assert any(sr.is_action for sr in get_search_results(request, query=sku[:5])) # Actions work assert empty_iterable(get_search_results(request, query=sku[:2])) # Short queries don't
def post(self, request, *args, **kwargs): order = self.object = self.get_object() new_status = OrderStatus.objects.get(pk=int(request.POST["status"])) if new_status.role == OrderStatusRole.COMPLETE and not order.can_set_complete(): raise Problem(_("Unable to set order as completed at this point")) old_status = order.status order.status = new_status order.save(update_fields=("status",)) message = _("Order status changed: %s \u2192 %s") % (old_status, new_status) order.add_log_entry(message, user=request.user, identifier="status_change") messages.success(self.request, message) return HttpResponseRedirect(get_model_url(self.get_object()))
def post(self, request, *args, **kwargs): order = self.object = self.get_object() new_status = OrderStatus.objects.get(pk=int(request.POST["status"])) if new_status.role == OrderStatusRole.COMPLETE and not order.can_set_complete(): raise Problem(_("Unable to set order as completed at this point")) old_status = order.status order.status = new_status order.save(update_fields=("status",)) message = _("Order status changed: %s to %s") % (old_status, new_status) order.add_log_entry(message, user=request.user, identifier="status_change") messages.success(self.request, message) return HttpResponseRedirect(get_model_url(self.get_object()))
def get_search_results(self, request, query): minimum_query_length = 3 if len(query) >= minimum_query_length: categories = Category.objects.filter( Q(translations__name__icontains=query) | Q(identifier__icontains=query)).distinct().order_by( "tree_id", "lft") for i, category in enumerate(categories[:10]): relevance = 100 - i yield SearchResult(text=six.text_type(category), url=get_model_url(category), category=self.category, relevance=relevance)
def form_valid(self, form): order = self.object amount = Money(form.cleaned_data["amount"], order.currency) if amount.value == 0: messages.error(self.request, _("Payment amount cannot be 0")) return self.form_invalid(form) try: payment = order.create_payment(amount, description="Manual payment") messages.success(self.request, _("Payment %s created.") % payment.payment_identifier) except NoPaymentToCreateException: messages.error(self.request, _("Order has already been paid")) return self.form_invalid(form) else: return HttpResponseRedirect(get_model_url(order))
def get_search_results(self, request, query): minimum_query_length = 3 if len(query) >= minimum_query_length: orders = Order.objects.filter( Q(identifier__istartswith=query) | Q(reference_number__istartswith=query) | Q(email__icontains=query) | Q(phone__icontains=query) ).order_by("-id")[:15] for i, order in enumerate(orders): relevance = 100 - i yield SearchResult( text=six.text_type(order), url=get_model_url(order), category=_("Orders"), relevance=relevance )
def get_search_results(self, request, query): minimum_query_length = 3 if len(query) >= minimum_query_length: orders = Order.objects.filter( Q(identifier__istartswith=query) | Q(reference_number__istartswith=query) | Q(email__icontains=query) | Q(phone__icontains=query)).order_by("-id")[:15] for i, order in enumerate(orders): relevance = 100 - i yield SearchResult(text=six.text_type(order), url=get_model_url(order), category=_("Orders"), relevance=relevance)
def get_context_data(self, **kwargs): context = super(EditScriptContentView, self).get_context_data(**kwargs) context["title"] = get_create_or_change_title(self.request, self.object) context["action_infos"] = Action.get_ui_info_map() context["condition_infos"] = Condition.get_ui_info_map() context["cond_op_names"] = get_enum_choices_dict(StepConditionOperator) context["step_next_names"] = get_enum_choices_dict(StepNext) context["toolbar"] = Toolbar([ JavaScriptActionButton( text="Save", icon="fa fa-save", extra_css_class="btn-success", onclick="ScriptEditor.save();return false" ), get_discard_button(get_model_url(self.object, "edit")) ]) return context
def get_search_results(self, request, query): minimum_query_length = 3 if len(query) >= minimum_query_length: categories = Category.objects.filter( Q(translations__name__icontains=query) | Q(identifier__icontains=query) ).distinct().order_by("tree_id", "lft") for i, category in enumerate(categories[:10]): relevance = 100 - i yield SearchResult( text=six.text_type(category), url=get_model_url(category), category=self.category, relevance=relevance )
def for_model(cls, model, **kwargs): """ Generate a NewActionButton for a model, auto-wiring the URL. :param model: Model class :rtype: shoop.admin.toolbar.NewActionButton|None """ if "url" not in kwargs: try: url = get_model_url(model, kind="new") except NoModelUrl: return None kwargs["url"] = url kwargs.setdefault("text", _("New %(model)s") % {"model": model._meta.verbose_name}) return cls(**kwargs)
def get_context_data(self, **kwargs): context = super(EditScriptContentView, self).get_context_data(**kwargs) context["title"] = get_create_or_change_title(self.request, self.object) context["action_infos"] = Action.get_ui_info_map() context["condition_infos"] = Condition.get_ui_info_map() context["cond_op_names"] = get_enum_choices_dict(StepConditionOperator) context["step_next_names"] = get_enum_choices_dict(StepNext) context["toolbar"] = Toolbar([ JavaScriptActionButton(text="Save", icon="fa fa-save", extra_css_class="btn-success", onclick="ScriptEditor.save();return false"), get_discard_button(get_model_url(self.object, "edit")) ]) return context
def render_text(self, obj): url = getattr(obj, "url", None) text = self.empty_text if obj: text = force_text(obj) if not url: try: url = get_model_url(obj) except NoModelUrl: pass if not url: url = "#" return mark_safe("<a class=\"browse-text\" href=\"%(url)s\" target=\"_blank\">%(text)s</a> " % { "text": escape(text), "url": escape(url), })
def get_toolbar(self): save_form_id = self.get_save_form_id() object = self.get_object() delete_url = reverse_lazy("shoop_admin:service_provider.delete", kwargs={"pk": object.pk}) toolbar = get_default_edit_toolbar(self, save_form_id, delete_url=delete_url) if self.object.pk: toolbar.append(URLActionButton( text=_("Create {service_name}").format( service_name=self.object.service_model._meta.verbose_name), icon="fa fa-plus", url="{model_url}?provider={id}".format( model_url=get_model_url(self.object.service_model, "new"), id=self.object.id), extra_css_class="btn-info" )) return toolbar
def handle_create(self, request): try: state = json.loads(request.body.decode("utf-8"))["state"] order = create_order_from_state(state, creator=request.user) messages.success(request, _("Order %(identifier)s created.") % vars(order)) return JsonResponse({ "success": True, "orderIdentifier": order.identifier, "url": get_model_url(order) }) except Exception as exc: tb = traceback.format_exc() message = _("Could not create order:") if isinstance(exc, ValidationError): # pragma: no branch message += "\n" + "\n".join(force_text(err) for err in exc.messages) else: message += " " + tb # pragma: no cover return JsonResponse({"success": False, "errorMessage": message}, status=400)
def get_success_url(self): next = self.request.REQUEST.get("__next") try: if next == "return": return self.get_return_url() elif next == "new": return self.get_new_url() except NoModelUrl: pass try: return super(CreateOrUpdateView, self).get_success_url() except ImproperlyConfigured: pass try: return get_model_url(self.object) except NoModelUrl: pass
def get_toolbar(self): save_form_id = self.get_save_form_id() object = self.get_object() delete_url = reverse_lazy("shoop_admin:service_provider.delete", kwargs={"pk": object.pk}) toolbar = get_default_edit_toolbar(self, save_form_id, delete_url=delete_url) if self.object.pk: toolbar.append( URLActionButton(text=_("Create {service_name}").format( service_name=self.object.service_model._meta.verbose_name), icon="fa fa-plus", url="{model_url}?provider={id}".format( model_url=get_model_url( self.object.service_model, "new"), id=self.object.id), extra_css_class="btn-info")) return toolbar
def save_form_parts(self, form): is_new = (not self.object.pk) form_parts = self.get_form_parts(self.object) for form_part in form_parts: retval = form_part.form_valid(form) if retval is not None: # Allow a form part to change the identity of the object self.object = retval for form_part in form_parts: form_part.object = self.object add_create_or_change_message(self.request, self.object, is_new) if hasattr(self, "get_success_url"): return HttpResponseRedirect(self.get_success_url()) if is_new: return HttpResponseRedirect(get_model_url(self.object)) else: return HttpResponseRedirect(self.request.path)
def model_url(model, kind="detail", default=None): """ Get a model URL of the given kind for a model (instance or class). :param model: The model instance or class. :type model: django.db.Model :param kind: The URL kind to retrieve. See `get_model_url`. :type kind: str :param default: Default value to return if model URL retrieval fails. If None, the `NoModelUrl` exception is (re)raised. :type default: str|None :return: URL string. :rtype: str """ try: return get_model_url(model, kind) except NoModelUrl: if default is None: raise return default
def get_search_results(self, request, query): minimum_query_length = 3 skus_seen = set() if len(query) >= minimum_query_length: pk_counter = Counter() pk_counter.update(Product.objects.filter(sku__startswith=query).values_list("pk", flat=True)) name_q = Q() for part in split_query(query, minimum_query_length): name_q &= Q(name__icontains=part) pk_counter.update( Product._parler_meta.root_model.objects.filter(name_q).values_list("master_id", flat=True) ) pks = [pk for (pk, count) in pk_counter.most_common(10)] for product in Product.objects.filter(pk__in=pks): relevance = 100 - pk_counter.get(product.pk, 0) skus_seen.add(product.sku.lower()) yield SearchResult( text=force_text(product), url=get_model_url(product), category=_("Products"), relevance=relevance ) if len(query) >= minimum_query_length: url = reverse("shoop_admin:product.new") if " " in query: yield SearchResult( text=_("Create Product Called \"%s\"") % query, url=manipulate_query_string(url, name=query), is_action=True ) else: if query.lower() not in skus_seen: yield SearchResult( text=_("Create Product with SKU \"%s\"") % query, url=manipulate_query_string(url, sku=query), is_action=True )
def form_valid(self, form): product_ids_to_quantities = dict( (int(key.replace("q_", "")), value) for (key, value) in six.iteritems(form.cleaned_data) if key.startswith("q_") and value > 0 ) order = self.object product_map = Product.objects.in_bulk(set(product_ids_to_quantities.keys())) products_to_quantities = dict( (product_map[product_id], quantity) for (product_id, quantity) in six.iteritems(product_ids_to_quantities) ) unsaved_shipment = Shipment(order=order, supplier=form.cleaned_data["supplier"]) for extend_class in get_provide_objects(FORM_MODIFIER_PROVIDER_KEY): extend_class().form_valid_hook(form, unsaved_shipment) try: shipment = order.create_shipment(product_quantities=products_to_quantities, shipment=unsaved_shipment) except NoProductsToShipException: messages.error(self.request, _("No products to ship.")) return self.form_invalid(form) else: messages.success(self.request, _("Shipment %s created.") % shipment.id) return HttpResponseRedirect(get_model_url(order))
def form_valid(self, form): product_ids_to_quantities = dict( (int(key.replace("q_", "")), value) for (key, value) in six.iteritems(form.cleaned_data) if key.startswith("q_") and value > 0) order = self.object product_map = Product.objects.in_bulk( set(product_ids_to_quantities.keys())) products_to_quantities = dict( (product_map[product_id], quantity) for (product_id, quantity) in six.iteritems(product_ids_to_quantities)) try: shipment = order.create_shipment( supplier=form.cleaned_data["supplier"], product_quantities=products_to_quantities) except NoProductsToShipException: messages.error(self.request, _("No products to ship.")) return self.form_invalid(form) else: messages.success(self.request, _("Shipment %s created.") % shipment.id) return HttpResponseRedirect(get_model_url(order))
def get(self, request, *args, **kwargs): return HttpResponseRedirect(get_model_url(self.get_object()))
def get_success_url(self): return get_model_url(self.get_contact())
def _get_variation_and_package_menu_items(self, product): variation_parent = product.is_variation_parent() variation_child = product.is_variation_child() package_parent = product.is_package_parent() variation_url = reverse("shoop_admin:product.edit_variation", kwargs={"pk": product.pk}) if variation_parent: yield DropdownDivider() yield DropdownHeader(text=_("Variations")) yield DropdownItem( text=_("Manage Variations"), icon="fa fa-sitemap", url=variation_url, ) for child in product.variation_children.all(): yield DropdownItem( text=_("Child: %s") % child, icon="fa fa-eye", url=get_model_url(child), ) elif variation_child: yield DropdownDivider() yield DropdownHeader(text=_("Variations")) parent = product.variation_parent yield DropdownItem( text=_("Manage Variations"), icon="fa fa-sitemap", url=variation_url, ) yield DropdownItem( text=_("Parent: %s") % parent, icon="fa fa-eye", url=get_model_url(parent), ) for sib in product.get_variation_siblings(): yield DropdownItem( text=_("Sibling: %s") % sib, icon="fa fa-eye", url=get_model_url(sib), ) elif package_parent: yield DropdownDivider() yield DropdownHeader(text=_("Variations")) yield DropdownItem( text=_("Manage Package"), icon="fa fa-cube", url="#", # TODO: Implement manage packages ) for child in product.get_all_package_children(): yield DropdownItem( text=_("Child: %s") % child, icon="fa fa-eye", url=get_model_url(child), ) package_parents = list(product.get_all_package_parents()) if package_parents: yield DropdownDivider() yield DropdownHeader(text=_("Variations")) for parent in package_parents: yield DropdownItem( text=_("Package Parent: %s") % parent, icon="fa fa-eye", url=get_model_url(parent), ) if not (variation_parent or variation_child or package_parent): yield DropdownDivider() yield DropdownHeader(text=_("Variations")) yield DropdownItem( text=_("Convert to Variation Parent"), icon="fa fa-retweet", url=variation_url, )
def get_object_url(self, instance): try: return get_model_url(instance) except NoModelUrl: pass return None
def get_new_url(self): return get_model_url(self.object, kind="new")
def get_return_url(self): return get_model_url(self.object, kind="list")
def get_success_url(self): return get_model_url(self.object)