def clean(self, value, model_instance): """ Remove potentially dangerous HTML tags and attributes. """ from mezzanine.conf import settings from mezzanine.core.defaults import (RICHTEXT_FILTER_LEVEL_NONE, RICHTEXT_FILTER_LEVEL_LOW) settings.use_editable() if settings.RICHTEXT_FILTER_LEVEL == RICHTEXT_FILTER_LEVEL_NONE: return value tags = settings.RICHTEXT_ALLOWED_TAGS attrs = settings.RICHTEXT_ALLOWED_ATTRIBUTES if settings.RICHTEXT_FILTER_LEVEL == RICHTEXT_FILTER_LEVEL_LOW: tags += LOW_FILTER_TAGS attrs += LOW_FILTER_ATTRS try: from bleach import clean except ImportError: return value else: return clean(value, tags=tags, attributes=attrs, strip=True, strip_comments=False)
def shop_feed(request, template="shop/feed.xml"): settings.use_editable() products = RetailProduct.objects.published() context = { "products": products, "uk_slow_rate": settings.UK_DELIVERY_SLOW_RATE, "uk_fast_rate": settings.UK_DELIVERY_FAST_RATE, "site_url": settings.SITE_URL, "site_title": settings.SITE_TITLE, } return render_to_response(template, context, RequestContext(request))
def getDQComments(self): # http://disqus.com/api/docs/posts/list/ # https://github.com/disqus/disqus-python from disqusapi import DisqusAPI from mezzanine.conf import settings settings.use_editable() disqus = DisqusAPI(settings.COMMENTS_DISQUS_API_SECRET_KEY, settings.COMMENTS_DISQUS_API_PUBLIC_KEY) posts = disqus.forums.listPosts(forum='digipal') for post in posts: print post print posts
def send_registration_confirmation_email(request): """ Send order receipt email on successful order. """ settings.use_editable() context = {"user": request.user, "site_url": settings.SITE_URL} template = "email/registration_confirmation" send_mail_template( "Thank you for registering with Manai", template, settings.SHOP_ORDER_FROM_EMAIL, request.user.email, context=context, fail_silently=settings.DEBUG)
def clean(self, value, model_instance): """ Remove potentially dangerous HTML tags and attributes. """ from mezzanine.conf import settings from mezzanine.conf.defaults import (RICHTEXT_FILTER_LEVEL_NONE, RICHTEXT_FILTER_LEVEL_LOW) settings.use_editable() if settings.RICHTEXT_FILTER_LEVEL == RICHTEXT_FILTER_LEVEL_NONE: return value tags = settings.RICHTEXT_ALLOWED_TAGS attrs = settings.RICHTEXT_ALLOWED_ATTRIBUTES if settings.RICHTEXT_FILTER_LEVEL == RICHTEXT_FILTER_LEVEL_LOW: tags += LOW_FILTER_TAGS attrs += LOW_FILTER_ATTRS return clean(value, tags=tags, attributes=attrs, strip=True)
def send_approve_mail(request, user): """ Sends an email to staff in listed in the setting ``ACCOUNTS_APPROVAL_EMAILS``, when a new user signs up and the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``. """ settings.use_editable() approval_emails = split_addresses(settings.ACCOUNTS_APPROVAL_EMAILS) if not approval_emails: return context = { "request": request, "user": user, "change_url": admin_url(user.__class__, "change", user.id), } subject = subject_template("email/account_approve_subject.txt", context) send_mail_template(subject, "email/account_approve", settings.DEFAULT_FROM_EMAIL, approval_emails, context=context)
def clean(self, value, model_instance): """ Remove potentially dangerous HTML tags and attributes. """ from mezzanine.conf import settings from mezzanine.core.defaults import RICHTEXT_FILTER_LEVEL_NONE, RICHTEXT_FILTER_LEVEL_LOW settings.use_editable() if settings.RICHTEXT_FILTER_LEVEL == RICHTEXT_FILTER_LEVEL_NONE: return value tags = settings.RICHTEXT_ALLOWED_TAGS attrs = settings.RICHTEXT_ALLOWED_ATTRIBUTES if settings.RICHTEXT_FILTER_LEVEL == RICHTEXT_FILTER_LEVEL_LOW: tags += LOW_FILTER_TAGS attrs += LOW_FILTER_ATTRS try: from bleach import clean except ImportError: return value else: return clean(value, tags=tags, attributes=attrs, strip=True, strip_comments=False)
def checkout_steps(request): """ Display the order form and handle processing of each step. """ # Do the authentication check here rather than using standard # login_required decorator. This means we can check for a custom # LOGIN_URL and fall back to our own login view. settings.use_editable() authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("checkout")) return HttpResponseRedirect(url) wholesale_logged_in = False user_fullname = "" if authenticated: user_fullname = " ".join([request.user.first_name, request.user.last_name]) if request.user.has_perm('custom.wholesale_customer'): wholesale_logged_in = True if float(request.cart.total_price()) < float(settings.WHOLESALE_MINIMUM_SPEND): return HttpResponseRedirect(reverse("basket")) # Determine the Form class to use during the checkout process form_class = get_callable(settings.SHOP_CHECKOUT_FORM_CLASS) step = int(request.POST.get("step", checkout.CHECKOUT_STEP_FIRST)) initial = checkout.initial_order_data(request) form = form_class(request, step, initial=initial) data = request.POST checkout_errors = [] if request.POST.get("back") is not None: # Back button in the form was pressed - load the order form # for the previous step and maintain the field values entered. step -= 1 form = form_class(request, step, initial=initial) elif request.method == "POST": form = form_class(request, step, initial=initial, data=data) if form.is_valid(): # Copy the current form fields to the session so that # they're maintained if the customer leaves the checkout # process, but remove sensitive fields from the session # such as the credit card fields so that they're never # stored anywhere. request.session["order"] = dict(form.cleaned_data) sensitive_card_fields = ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv") for field in sensitive_card_fields: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: try: billship_handler(request, form) except checkout.CheckoutError, e: checkout_errors.append(e) form.set_discount() # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the inital order object so that # the payment handler has access to all of the order # fields. If there is a payment error then delete the # order, otherwise remove the cart items from stock # and send the order reciept email. order = form.save(commit=False) order.setup(request) # Try payment. try: if order.total == 0: # FOR GROUPONS import datetime transaction_id = "GROUPON-%s" % str(datetime.datetime.now()).replace(' ','-') else: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError, e: # Error in payment handler. order.delete() checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: # Finalize order - ``order.complete()`` performs # final cleanup of session and cart. # ``order_handler()`` can be defined by the # developer to implement custom order processing. # Then send the order email to the customer. order.transaction_id = transaction_id order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order) # Set the cookie for remembering address details # if the "remember" checkbox was checked. response = HttpResponseRedirect(reverse("complete")) if form.cleaned_data.get("remember") is not None: remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") # Now add the customer to the CAMPAIGN MONITOR # subscriber list if they opted in addtolist = False if authenticated: if request.user.get_profile().optin: addtolist = True else: if bool(form.cleaned_data.get("optin")): addtolist = True if addtolist: cm_api = CampaignMonitorApi(settings.CM_API_KEY, settings.CM_CLIENT_ID) listid = settings.CM_RETAIL_LIST_ID custom_fields = {} if wholesale_logged_in: listid = settings.CM_WHOLESALE_LIST_ID usertype = USER_TYPE_CHOICES[request.user.get_profile().user_type] custom_fields = {"CustomerType": usertype} try: cm_api.subscriber_add( listid, form.cleaned_data.get("billing_detail_email"), form.cleaned_data.get("billing_detail_first_name") + ' ' + form.cleaned_data.get("billing_detail_last_name"), custom_fields=custom_fields) except: pass return response # If any checkout errors, assign them to a new form and # re-run is_valid. If valid, then set form to the next step. form = form_class(request, step, initial=initial, data=data, errors=checkout_errors) if form.is_valid(): step += 1 form = form_class(request, step, initial=initial)
def cart(request, template="shop/cart.html"): """ Display cart and handle removing items from the cart. """ settings.use_editable() wholesale_minimum_spend = float(settings.WHOLESALE_MINIMUM_SPEND) total = float(request.cart.total_price()) cart_formset = CartItemFormSet(instance=request.cart) discount_form = DiscountForm(request, request.POST or None) wholesale_logged_in = False user_fullname = "" if request.user.is_authenticated(): user_fullname = " ".join([request.user.first_name, request.user.last_name]) if request.user.has_perm('custom.wholesale_customer'): wholesale_logged_in = True # if not "applied" in request.session: # if total > 55.0 and not wholesale_logged_in: # discount_form = DiscountForm(request, {"discount_code": "5005XtYTR"}) # discount_form.set_discount() # request.session["applied"] = False # else: # request.session["applied"] = True # else: # request.session["applied"] = True request.session["applied"] = True build_your_own = False nextstep = "" if u"build_your_own" in request.session: build_your_own = request.session['build_your_own'] nextstep = request.session['nextstep'] if request.method == "POST": valid = True if request.POST.get("update_cart"): valid = request.cart.has_items() if not valid: # Session timed out. info(request, "Your cart has expired") else: cart_formset = CartItemFormSet(request.POST, instance=request.cart) valid = cart_formset.is_valid() if valid: cart_formset.save() recalculate_discount(request) info(request, "Cart updated") request.session["applied"] = True else: valid = discount_form.is_valid() if valid: discount_form.set_discount() request.session["applied"] = True if valid: return HttpResponseRedirect(reverse("basket")) context = { "cart_formset": cart_formset, "wholesale_logged_in": wholesale_logged_in, "user_fullname": user_fullname, "wholesale_minimum_spend": int(wholesale_minimum_spend), "total": total, "build_your_own": build_your_own, "build_your_own_nextstep": nextstep, "discount_applied": request.session["applied"], } settings.use_editable() if (settings.SHOP_DISCOUNT_FIELD_IN_CART and DiscountCode.objects.active().count() > 0): context["discount_form"] = discount_form return render_to_response(template, context, RequestContext(request))
def wholesale_product(request, slug, template="shop/product.html"): """ Display a product - convert the product variations to JSON as well as handling adding the product to either the cart or the wishlist. """ #published_products = Product.objects.published(for_user=request.user) # Can't get this to work with WholesaleProduct published_products = WholesaleProduct.objects.published() product = get_object_or_404(published_products, slug=slug) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) add_product_form = "" wholesale_logged_in = False user_fullname = "" if request.user.is_authenticated(): user_fullname = " ".join([request.user.first_name, request.user.last_name]) if request.user.has_perm('custom.wholesale_customer'): wholesale_logged_in = True add_product_form = AddProductForm(request.POST or None, product=product, initial={"quantity": 1}, to_cart=to_cart) if request.method == "POST": if add_product_form.is_valid(): if to_cart: quantity = add_product_form.cleaned_data["quantity"] request.cart.add_item(add_product_form.variation, quantity, "wholesale-shop") recalculate_discount(request) info(request, "Item added to cart") return redirect("basket") else: skus = request.wishlist sku = add_product_form.variation.sku if sku not in skus: skus.append(sku) info(request, "Item added to wishlist") response = redirect("shop_wishlist") set_cookie(response, "wishlist", ",".join(skus)) return response fields = [f.name for f in ProductVariation.option_fields()] fields += ["sku", "image_id"] variations = product.variations.all() variations_json = simplejson.dumps([dict([(f, getattr(v, f)) for f in fields]) for v in variations]) settings.use_editable() wholesale_minimum_spend = float(settings.WHOLESALE_MINIMUM_SPEND) context = { "product": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related": product.related_products.published(for_user=request.user), "add_product_form": add_product_form, "shop_slug": "wholesale-shop", "wholesale_logged_in": wholesale_logged_in, "user_fullname": user_fullname, "wholesale_minimum_spend": wholesale_minimum_spend, } return render(request, template, context)
def billship_handler(request, order_form): from mezzanine.conf import settings from cartridge.shop.utils import set_shipping, sign settings.use_editable() set_shipping(request, _("Flat rate shipping"), settings.SHOP_DEFAULT_SHIPPING_VALUE)