def comment(request, template="generic/comments.html"): """ Handle a ``ThreadedCommentForm`` submission and redirect back to its related object. """ try: model = get_model(*request.POST["content_type"].split(".", 1)) obj = model.objects.get(id=request.POST["object_pk"]) if request.method != "POST": raise ObjectDoesNotExist() except (KeyError, TypeError, AttributeError, ObjectDoesNotExist): # Something was missing from the post so abort. return HttpResponseRedirect("/") form = ThreadedCommentForm(request, obj, request.POST or None) if form.is_valid(): comment = form.get_comment_object() if request.user.is_authenticated(): comment.user = request.user comment.by_author = request.user == getattr(obj, "user", None) comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"]) comment.replied_to_id = request.POST.get("replied_to") comment.save() response = HttpResponseRedirect(comment.get_absolute_url()) # Store commenter's details in a cookie for 90 days. cookie_expires = 60 * 60 * 24 * 90 for field in ThreadedCommentForm.cookie_fields: cookie_name = ThreadedCommentForm.cookie_prefix + field cookie_value = request.POST.get(field, "") set_cookie(response, cookie_name, cookie_value, cookie_expires) return response else: # Show errors with stand-alone comment form. context = {"obj": obj, "posted_comment_form": form} return render(request, template, context)
def rating(request): """ Handle a ``RatingForm`` submission and redirect back to its related object. """ try: model = get_model(*request.POST["content_type"].split(".", 1)) obj = model.objects.get(id=request.POST["object_pk"]) url = obj.get_absolute_url() + "#rating-%s" % obj.id except (KeyError, TypeError, AttributeError, ObjectDoesNotExist): # Something was missing from the post so abort. return HttpResponseRedirect("/") try: rating_value = int(request.POST["value"]) except (KeyError, ValueError): return HttpResponseRedirect(url) ratings = request.COOKIES.get("mezzanine-rating", "").split(",") rating_string = "%s.%s" % (request.POST["content_type"], request.POST["object_pk"]) if rating_string in ratings: # Already rated so abort. return HttpResponseRedirect(url) obj.rating.add(Rating(value=rating_value)) response = HttpResponseRedirect(url) ratings.append(rating_string) expiry = 60 * 60 * 24 * 365 set_cookie(response, "mezzanine-rating", ",".join(ratings), expiry) return response
def rating(request): """ Handle a ``RatingForm`` submission and redirect back to its related object. """ response = initial_validation(request, "rating") if isinstance(response, HttpResponse): return response obj, post_data = response url = add_cache_bypass(obj.get_absolute_url().split("#")[0]) response = redirect(url + "#rating-%s" % obj.id) rating_form = RatingForm(request, obj, post_data) if rating_form.is_valid(): rating_form.save() if request.is_ajax(): # Reload the object and return the rating fields as json. obj = obj.__class__.objects.get(id=obj.id) rating_name = obj.get_ratingfield_name() json = {} for f in ("average", "count", "sum"): json["rating_" + f] = getattr(obj, "%s_%s" % (rating_name, f)) response = HttpResponse(dumps(json)) ratings = ",".join(rating_form.previous + [rating_form.current]) set_cookie(response, "mezzanine-rating", ratings) return response
def rating(request): """ Handle a ``RatingForm`` submission and redirect back to its related object. """ try: model = get_model(*request.POST["content_type"].split(".", 1)) obj = model.objects.get(id=request.POST["object_pk"]) url = obj.get_absolute_url() + "#rating-%s" % obj.id field = getattr(obj, request.POST["field_name"]) if field.model != Rating: raise TypeError("Not a rating field.") except (KeyError, TypeError, AttributeError, ObjectDoesNotExist): # Something was missing from the post so abort. return HttpResponseRedirect("/") try: rating_value = int(request.POST["value"]) except (KeyError, ValueError): return HttpResponseRedirect(url) rated = request.COOKIES.get("mezzanine-rating", "").split(",") cookie = "%(content_type)s.%(object_pk)s.%(field_name)s" % request.POST if cookie in rated: # Already rated so abort. return HttpResponseRedirect(url) field.add(Rating(value=rating_value)) response = HttpResponseRedirect(url) rated.append(cookie) expiry = 60 * 60 * 24 * 365 set_cookie(response, "mezzanine-rating", ",".join(rated), expiry) return response
def comment(request, template="generic/comments.html", extra_context=None): """ Handle a ``ThreadedCommentForm`` submission and redirect back to its related object. """ response = initial_validation(request, "comment") if isinstance(response, HttpResponse): return response obj, post_data = response form_class = import_dotted_path(settings.COMMENT_FORM_CLASS) form = form_class(request, obj, post_data) if form.is_valid(): url = obj.get_absolute_url() if is_spam(request, form, url): return redirect(url) comment = form.save(request) response = redirect(add_cache_bypass(comment.get_absolute_url())) # Store commenter's details in a cookie for 90 days. for field in ThreadedCommentForm.cookie_fields: cookie_name = ThreadedCommentForm.cookie_prefix + field cookie_value = post_data.get(field, "") set_cookie(response, cookie_name, cookie_value) return response elif request.is_ajax() and form.errors: return HttpResponse(dumps({"errors": form.errors})) # Show errors with stand-alone comment form. context = {"obj": obj, "posted_comment_form": form} context.update(extra_context or {}) return TemplateResponse(request, template, context)
def rating(request): """ Handle a ``RatingForm`` submission and redirect back to its related object. """ try: model = get_model(*request.POST["content_type"].split(".", 1)) obj = model.objects.get(id=request.POST["object_pk"]) url = obj.get_absolute_url() + "#rating-%s" % obj.id except (KeyError, TypeError, AttributeError, ObjectDoesNotExist): # Something was missing from the post so abort. return HttpResponseRedirect("/") try: rating_value = int(request.POST["value"]) except (KeyError, ValueError): return HttpResponseRedirect(url) # There can only be one ``RatingField``, find its manager. for field in obj._meta.many_to_many: if isinstance(field, RatingField): rating_manager = getattr(obj, field.name) break else: raise TypeError("%s doesn't contain a RatingField." % obj) ratings = request.COOKIES.get("mezzanine-rating", "").split(",") rating_string = "%s.%s" % (request.POST["content_type"], request.POST["object_pk"]) if rating_string in ratings: # Already rated so abort. return HttpResponseRedirect(url) rating_manager.add(Rating(value=rating_value)) response = HttpResponseRedirect(url) ratings.append(rating_string) expiry = 60 * 60 * 24 * 365 set_cookie(response, "mezzanine-rating", ",".join(ratings), expiry) return response
def comment(request, template="generic/comments.html"): """ Handle a ``ReviewForm`` submission and redirect back to its related object. """ response = initial_validation(request, "comment") if isinstance(response, HttpResponse): return response obj, post_data = response form = ReviewForm(request, obj, request.POST ) if form.is_valid(): url = obj.get_absolute_url() if is_spam(request, form, url): return redirect(url) comment = form.save(request) response = redirect(add_cache_bypass(comment.get_absolute_url())) # Store commenter's details in a cookie for 90 days. for field in ReviewForm.cookie_fields: cookie_name = ReviewForm.cookie_prefix + field cookie_value = post_data.get(field, "") set_cookie(response, cookie_name, cookie_value) """ Send activity feed to those who follow this vendor page. """ if request.user.is_authenticated(): action.send(obj, verb=settings.GOT_REVIEW_VERB, target=comment ) return response elif request.is_ajax() and form.errors: return HttpResponse(dumps({"errors": form.errors})) # Show errors with stand-alone comment form. context = {"obj": obj, "posted_comment_form": form} response = render(request, template, context) return response
def polling(request, slug=None): blog_posts = BlogPost.objects.published(for_user=request.user) blog_post = blog_posts.get(slug=slug) url = request.build_absolute_uri() url = url.split('/') url = '/'.join(url[:-2]) + '/' if not blog_post: return HttpResponse(json.dumps({'result':'Sorry, no such post'}), mimetype="application/json") try: rating_value = request.GET["value"] except (KeyError, ValueError): return HttpResponseRedirect(url) ratings = request.COOKIES.get("poll-rating", "").split(",") rating_string = "%s.%s" % ('blogpost', blog_post.id) #"\054blog_fork.blogpost.2\054blog_fork.blogpost.1" if rating_string in ratings: # Already rated so abort. return HttpResponse(json.dumps({'result':'You have already voted'}), mimetype="application/json") if rating_value == 'up': blog_post.upvote +=1 blog_post.save() if rating_value == 'down': blog_post.downvote +=1 blog_post.save() response = HttpResponse(json.dumps({'result':rating_value}), mimetype="application/json") ratings.append(rating_string) expiry = 60 * 60 * 24 * 365 set_cookie(response, "poll-rating", ",".join(ratings), expiry) return response
def handle_wishlist(request, slug, form_class=AddProductForm): if request.method == 'POST' and request.is_ajax(): published_products = Product.objects.published(for_user=request.user) product = get_object_or_404(published_products, slug=slug) initial_data = {} variations = product.variations.all() fields = [f.name for f in ProductVariation.option_fields()] if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = form_class(request.POST or None, product=product, initial=initial_data, to_cart=False) if add_product_form.is_valid(): skus = request.wishlist sku = add_product_form.variation.sku if sku not in skus: skus.append(sku) messages.info(request, _("Item added to wishlist")) response = render(request, 'messages.html') set_cookie(response, "wishlist", ",".join(skus)) return response return HttpResponse(json.dumps(add_product_form.errors), content_type="application/json") return HttpResponse('not post')
def 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) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = simplejson.dumps([ dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations ]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = AddProductForm(request.POST or None, product=product, initial=initial_data, 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) recalculate_cart(request) info(request, _("Item added to cart")) return redirect("shop_cart") 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 context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": product.related_products.published(for_user=request.user), "add_product_form": add_product_form } templates = [u"shop/%s.html" % unicode(product.slug), template] return render(request, templates, context)
def comment(request, template="generic/comments.html"): """ Handle a ``ThreadedCommentForm`` submission and redirect back to its related object. """ response = initial_validation(request, "comment") if isinstance(response, HttpResponse): return response obj, post_data = response form = ThreadedCommentForm(request, obj, post_data) if form.is_valid(): url = obj.get_absolute_url() if is_spam(request, form, url): return redirect(url) comment = form.save(request) response = redirect(add_cache_bypass(comment.get_absolute_url())) # Store commenter's details in a cookie for 90 days. for field in ThreadedCommentForm.cookie_fields: cookie_name = ThreadedCommentForm.cookie_prefix + field cookie_value = post_data.get(field, "") set_cookie(response, cookie_name, cookie_value) return response elif request.is_ajax() and form.errors: return HttpResponse(dumps({"errors": form.errors})) # Show errors with stand-alone comment form. context = {"obj": obj, "posted_comment_form": form} response = render(request, template, context) return response
def set_device(request, device=""): """ Sets a device name in a cookie when a user explicitly wants to go to the site for a particular device (eg mobile). """ response = HttpResponseRedirect(request.GET.get("next", "/")) set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365) return response
def set_device(request, device=""): """ Sets a device name in a cookie when a user explicitly wants to go to the site for a particular device (eg mobile). """ response = redirect(add_cache_bypass(next_url(request) or "/")) set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365) return response
def set_device(request, device=""): """ Sets a device name in a cookie when a user explicitly wants to go to the site for a particular device (eg mobile). """ response = redirect(add_cache_bypass(request.GET.get("next", "/"))) set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365) return response
def product(request, slug, template="shop/product.html", form_class=AddProductForm, extra_context=None): """ 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) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = dumps([dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = form_class(request.POST or None, product=product, initial=initial_data, 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) recalculate_cart(request) info(request, _("Item added to cart")) return redirect("shop:shop_cart") 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:shop_wishlist") set_cookie(response, "wishlist", ",".join(skus)) return response related = [] if settings.SHOP_USE_RELATED_PRODUCTS: related = product.related_products.published(for_user=request.user) context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": related, "add_product_form": add_product_form } context.update(extra_context or {}) templates = [u"shop/%s.html" % str(product.slug), template] # Check for a template matching the page's content model. if getattr(product, 'content_model', None) is not None: templates.insert(0, u"shop/products/%s.html" % product.content_model) return TemplateResponse(request, templates, context)
def product(request, slug, template="shop/product.html", form_class=AddProductForm, extra_context=None): """ 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) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = dumps([dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = form_class(request.POST or None, product=product, initial=initial_data, 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) recalculate_cart(request) info(request, _("Item added to cart")) return redirect("shop_cart") 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 related = [] if settings.SHOP_USE_RELATED_PRODUCTS: related = product.related_products.published(for_user=request.user) context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": related, "add_product_form": add_product_form } context.update(extra_context or {}) templates = [u"shop/%s.html" % str(product.slug), template] # Check for a template matching the page's content model. if getattr(product, 'content_model', None) is not None: templates.insert(0, u"shop/products/%s.html" % product.content_model) return TemplateResponse(request, templates, context)
def comment(request, template="generic/comments.html"): """ Handle a ``ThreadedCommentForm`` submission and redirect back to its related object. """ post_data = request.POST settings.use_editable() if settings.COMMENTS_ACCOUNT_REQUIRED: if not request.user.is_authenticated(): # Account required but user isn't authenticated - store # their post data in the session and redirect to login. request.session["unauthenticated_comment"] = post_data error(request, _("You must log in to comment. Please log in or " "sign up, and your comment will be posted.")) url = "%s?next=%s" % (settings.LOGIN_URL, reverse("comment")) return redirect(url) elif "unauthenticated_comment" in request.session: # User has logged in after post data being stored in the # session for an unauthenticated comment post, so use it. post_data = request.session.pop("unauthenticated_comment") try: model = get_model(*post_data["content_type"].split(".", 1)) obj = model.objects.get(id=post_data["object_pk"]) except (KeyError, TypeError, AttributeError, ObjectDoesNotExist): # Something was missing from the post so abort. return HttpResponseRedirect("/") form = ThreadedCommentForm(request, obj, post_data) if form.is_valid(): url = obj.get_absolute_url() if is_spam(request, form, url): return redirect(url) comment = form.get_comment_object() if request.user.is_authenticated(): comment.user = request.user comment.by_author = request.user == getattr(obj, "user", None) comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"]) comment.replied_to_id = post_data.get("replied_to") comment.save() comment_was_posted.send(sender=comment.__class__, comment=comment, request=request) url = add_cache_bypass(comment.get_absolute_url()) response = HttpResponseRedirect(url) # Store commenter's details in a cookie for 90 days. cookie_expires = 60 * 60 * 24 * 90 for field in ThreadedCommentForm.cookie_fields: cookie_name = ThreadedCommentForm.cookie_prefix + field cookie_value = post_data.get(field, "") set_cookie(response, cookie_name, cookie_value, cookie_expires) return response else: # Show errors with stand-alone comment form. context = {"obj": obj, "posted_comment_form": form} return render(request, template, context)
def comment(request, template="generic/comments.html"): """ Handle a ``ThreadedCommentForm`` submission and redirect back to its related object. """ post_data = request.POST settings.use_editable() if settings.COMMENTS_ACCOUNT_REQUIRED: if not request.user.is_authenticated(): # Account required but user isn't authenticated - store # their post data in the session and redirect to login. request.session["unauthenticated_comment"] = post_data error(request, _("You must log in to comment. Please log in or " "sign up, and your comment will be posted.")) url = "%s?next=%s" % (settings.LOGIN_URL, reverse("comment")) return redirect(url) elif "unauthenticated_comment" in request.session: # User has logged in after post data being stored in the # session for an unauthenticated comment post, so use it. post_data = request.session.pop("unauthenticated_comment") try: model = get_model(*post_data["content_type"].split(".", 1)) obj = model.objects.get(id=post_data["object_pk"]) except (KeyError, TypeError, AttributeError, ObjectDoesNotExist): # Something was missing from the post so abort. return HttpResponseRedirect("/") form = ThreadedCommentForm(request, obj, post_data) if form.is_valid(): url = obj.get_absolute_url() if is_spam(request, form, url): return redirect(url) comment = form.get_comment_object() if request.user.is_authenticated(): comment.user = request.user comment.by_author = request.user == getattr(obj, "user", None) comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"]).split(',')[0].strip() comment.replied_to_id = post_data.get("replied_to") comment.save() comment_was_posted.send(sender=comment.__class__, comment=comment, request=request) url = add_cache_bypass(comment.get_absolute_url()) response = HttpResponseRedirect(url) # Store commenter's details in a cookie for 90 days. cookie_expires = 60 * 60 * 24 * 90 for field in ThreadedCommentForm.cookie_fields: cookie_name = ThreadedCommentForm.cookie_prefix + field cookie_value = post_data.get(field, "") set_cookie(response, cookie_name, cookie_value, cookie_expires) return response else: # Show errors with stand-alone comment form. context = {"obj": obj, "posted_comment_form": form} return render(request, template, context)
def set_device(request, device=""): """ Sets a device name in a cookie when a user explicitly wants to go to the site for a particular device (eg mobile). """ url = request.GET.get("next", "/") url += "?" if "?" not in url else "&" url += "device-time=" + str(time()).replace(".", "") response = redirect(url) set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365) return response
def remove_wishlist_item(request): if request.method == 'POST': skus = request.wishlist sku = request.POST.get("sku") if sku in skus: skus.remove(sku) message = _("Item removed from wishlist") messages.info(request, message) response = render(request,'messages.html') set_cookie(response, "wishlist", ",".join(skus)) return response
def remove_wishlist_item(request): if request.method == 'POST': skus = request.wishlist sku = request.POST.get("sku") if sku in skus: skus.remove(sku) message = _("Item removed from wishlist") messages.info(request, message) response = render(request, 'messages.html') set_cookie(response, "wishlist", ",".join(skus)) return response
def wishlist( request, template="shop/wishlist.html", form_class=AddProductForm, extra_context=None, ): """ Display the wishlist and handle removing items from the wishlist and adding them to the cart. """ if not settings.SHOP_USE_WISHLIST: raise Http404 skus = request.wishlist error = None if request.method == "POST": to_cart = request.POST.get("add_cart") add_product_form = form_class(request.POST or None, to_cart=to_cart) if to_cart: if add_product_form.is_valid(): request.cart.add_item(add_product_form.variation, 1) recalculate_cart(request) message = _("Item added to cart") url = "shop_cart" else: error = list(add_product_form.errors.values())[0] else: message = _("Item removed from wishlist") url = "shop_wishlist" sku = request.POST.get("sku") if sku in skus: skus.remove(sku) if not error: info(request, message) response = redirect(url) set_cookie(response, "wishlist", ",".join(skus)) return response # Remove skus from the cookie that no longer exist. published_products = Product.objects.published(for_user=request.user) f = {"product__in": published_products, "sku__in": skus} wishlist = ProductVariation.objects.filter(**f).select_related("product") wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku)) context = {"wishlist_items": wishlist, "error": error} context.update(extra_context or {}) response = TemplateResponse(request, template, context) if len(wishlist) < len(skus): skus = [variation.sku for variation in wishlist] set_cookie(response, "wishlist", ",".join(skus)) return response
def 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) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = simplejson.dumps([dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = AddProductForm(request.POST or None, product=product, initial=initial_data, 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) recalculate_discount(request) recalculate_billship_tax(request) info(request, _("Item added to cart")) return redirect("shop_cart") 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 context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": product.related_products.published( for_user=request.user), "add_product_form": add_product_form } templates = [u"shop/%s.html" % unicode(product.slug), template] return render(request, templates, context)
def wishlist(request, template="shop/wishlist.html", form_class=AddProductForm, extra_context=None): """ Display the wishlist and handle removing items from the wishlist and adding them to the cart. """ if not settings.SHOP_USE_WISHLIST: raise Http404 skus = request.wishlist error = None if request.method == "POST": to_cart = request.POST.get("add_cart") add_product_form = form_class(request.POST or None, to_cart=to_cart) if to_cart: if add_product_form.is_valid(): request.cart.add_item(add_product_form.variation, 1) recalculate_cart(request) message = _("Item added to cart") url = "shop_cart" else: error = list(add_product_form.errors.values())[0] else: message = _("Item removed from wishlist") url = "shop_wishlist" sku = request.POST.get("sku") if sku in skus: skus.remove(sku) if not error: info(request, message) response = redirect(url) set_cookie(response, "wishlist", ",".join(skus)) return response # Remove skus from the cookie that no longer exist. published_products = Product.objects.published(for_user=request.user) f = {"product__in": published_products, "sku__in": skus} wishlist = ProductVariation.objects.filter(**f).select_related("product") wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku)) context = {"wishlist_items": wishlist, "error": error} context.update(extra_context or {}) response = TemplateResponse(request, template, context) if len(wishlist) < len(skus): skus = [variation.sku for variation in wishlist] set_cookie(response, "wishlist", ",".join(skus)) return response
def handle_comments(obj, request): """ A problem exists with having a single URL to handle posting generic data. If there's an error with the form, we have to either display the form with errors on a different page than the page where the form was originally rendered, or redirect back to the original page and lose the form errors. This function can be called from any view that contains comments. It returns a 3-item sequence containing two forms, one with posted data and one without, which are each used to build the threaded comment tree with forms for replying. The third item returned is a response object to redirect to if a comment is successfully posted. """ # Create two comment forms - one with posted data and errors that will be # matched to the form submitted via comment_id, and an empty one for all # other instances. cookie_prefix = "mezzanine-comment-" cookie_fields = ("user_name", "user_email", "user_url") initial = {} for field in cookie_fields: initial[field] = request.COOKIES.get(cookie_prefix + field, "") posted = request.POST or None posted_comment_form = ThreadedCommentForm(obj, posted, initial=initial) unposted_comment_form = ThreadedCommentForm(obj, initial=initial) response = None if request.method == "POST" and posted_comment_form.is_valid(): comment = posted_comment_form.get_comment_object() comment.by_author = request.user == getattr(obj, "user", None) comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"]) comment.replied_to_id = request.POST.get("replied_to") comment.save() #blog_post.comments.add(comment) response = HttpResponseRedirect(comment.get_absolute_url()) # Store commenter's details in a cookie for 90 days. cookie_expires = 60 * 60 * 24 * 90 for field in cookie_fields: cookie_name = cookie_prefix + field cookie_value = request.POST.get(field, "") set_cookie(response, cookie_name, cookie_value, cookie_expires) return posted_comment_form, unposted_comment_form, response
def blog_post_detail(request, slug, template="blog/blog_post_detail.html"): """ Display a blog post. """ # Create two comment forms - one with posted data and errors that will be # matched to the form submitted via comment_id, and an empty one for all # other instances. commenter_cookie_prefix = "mezzanine-blog-" commenter_cookie_fields = ("name", "email", "website") comment_data = {} for f in commenter_cookie_fields: comment_data[f] = request.COOKIES.get(commenter_cookie_prefix + f, "") blog_posts = BlogPost.objects.published(for_user=request.user) blog_post = get_object_or_404(blog_posts, slug=slug) posted_comment_form = CommentForm(request.POST or None, initial=comment_data) unposted_comment_form = CommentForm(initial=comment_data) if request.method == "POST" and posted_comment_form.is_valid(): comment = posted_comment_form.save(commit=False) comment.blog_post = blog_post comment.by_author = (request.user == blog_post.user and request.user.is_authenticated) comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"]) comment.replied_to_id = request.POST.get("replied_to") comment.save() response = HttpResponseRedirect(comment.get_absolute_url()) # Store commenter's details in a cookie for 90 days. cookie_expires = 60 * 60 * 24 * 90 for f in commenter_cookie_fields: cookie_name = commenter_cookie_prefix + f cookie_value = request.POST.get(f, "") set_cookie(response, cookie_name, cookie_value, cookie_expires) return response settings.use_editable() context = {"blog_post": blog_post, "blog_page": blog_page(), "use_disqus": bool(settings.COMMENTS_DISQUS_SHORTNAME), "posted_comment_form": posted_comment_form, "unposted_comment_form": unposted_comment_form} request_context = RequestContext(request, context) t = select_template(["blog/%s.html" % slug, template], request_context) return HttpResponse(t.render(request_context))
def render(self, request): from mezzanine.blog.forms import CommentForm commenter_cookie_prefix = "mezzanine-blog-" commenter_cookie_fields = ("name", "email", "website") comment_data = {} for f in commenter_cookie_fields: comment_data[f] = request.COOKIES.get(commenter_cookie_prefix + f, "") saved = False if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = self comment.by_author = (request.user == self.user and request.user.is_authenticated) comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"]) comment.replied_to_id = request.POST.get("replied_to") comment.save() saved = True else: comment_data = {} for f in commenter_cookie_fields: comment_data[f] = request.COOKIES.get(commenter_cookie_prefix + f, "") form = CommentForm(initial=comment_data) context = {"displayable": self, "form": form, "saved": saved, } response = HttpResponse(self.blog.get_post_template().render(RequestContext(request, context))) if saved: cookie_expires = 60 * 60 * 24 * 90 for f in commenter_cookie_fields: cookie_name = commenter_cookie_prefix + f cookie_value = request.POST.get(f, "") set_cookie(response, cookie_name, cookie_value, cookie_expires) return response
def rating(request): """ Handle a ``RatingForm`` submission and redirect back to its related object. """ response = initial_validation(request, "rating") if isinstance(response, HttpResponse): return response obj, post_data = response url = obj.get_absolute_url() url = add_cache_bypass(url.split("#")[0]) + "#rating-%s" % obj.id response = redirect(url) rating_form = RatingForm(request, obj, post_data) if rating_form.is_valid(): rating_form.save() if request.is_ajax(): # Reload the object and return the new rating. obj = obj.__class__.objects.get(id=obj.id) fields = ("rating_avg", "rating_count", "rating_sum") json = dumps(dict([(f, getattr(obj, f)) for f in fields])) response = HttpResponse(json) ratings = ",".join(rating_form.previous + [rating_form.current]) set_cookie(response, "mezzanine-rating", ratings) return response
def handle_wishlist(request, slug, form_class=AddProductForm): if request.method == 'POST' and request.is_ajax(): published_products = Product.objects.published(for_user=request.user) product = get_object_or_404(published_products, slug=slug) initial_data = {} variations = product.variations.all() fields = [f.name for f in ProductVariation.option_fields()] if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = form_class(request.POST or None, product=product, initial=initial_data, to_cart=False) if add_product_form.is_valid(): skus = request.wishlist sku = add_product_form.variation.sku if sku not in skus: skus.append(sku) messages.info(request, _("Item added to wishlist")) response = render(request,'messages.html') set_cookie(response, "wishlist", ",".join(skus)) return response return HttpResponse(json.dumps(add_product_form.errors), content_type="application/json") return HttpResponse('not post')
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. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) # Level C Discount if request.user.profile.is_level_C: request.session['force_discount'] = 'l3v3lC15' # Determine the Form class to use during the checkout process form_class = get_callable(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) cancelled = request.GET.get('c', None) if not cancelled: step = int(request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) else: step = checkout.CHECKOUT_STEP_FIRST form = form_class(request, step, initial=initial) data = request.POST checkout_errors = [] log.debug('Checkout step %s' % step) 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" and request.cart.has_items(): 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: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: try: billship_handler(request, form) tax_handler(request, form) except checkout.CheckoutError, e: checkout_errors.append(e) form.set_discount() if form.cleaned_data.get('payment_method') == 'paypal': step += 1 try: request.session["order"]["step"] = step request.session.modified = True except KeyError: pass return redirect(Paypal.process(request, form)) # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the initial 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 receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: 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. if form.cleaned_data.get('payment_method') == 'paypal': payment = Paypal.find(request) if payment.shipping_info: order.shipping_detail_first_name = payment.shipping_info.first_name order.shipping_detail_last_name = payment.shipping_info.last_name order.shipping_detail_street = payment.shipping_info.address.line1 order.shipping_detail_city = payment.shipping_info.address.city order.shipping_detail_state = payment.shipping_info.address.state order.shipping_detail_postcode = payment.shipping_info.address.postal_code order.shipping_detail_country = payment.shipping_info.address.country_code 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 = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") 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 checkout_steps(request, form_class=OrderForm): """ Display the order form and handle processing of each step. """ #cart(request) # 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. authenticated = request.user.is_authenticated() onekey = request.GET.get('keycode', None) checkout_errors = [] #add get instead of request.session['onekeycode'] #when homepage change to network+ style, weixin onekey order error that no onekeycode in session #but pc is OK, guess due to cookie forbidden within weixin browser, not diginto yet, just workaround here if onekey and onekey != request.session.get('onekeycode', None): #raise Exception('code got right!') #checkout_errors.append('您可能存在恶意下单,请联系客服,非常抱歉给您带来不便!') pass if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated and not onekey: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) #wni: add here for weixin pay #weixincode = request.GET.get('code',None) if settings.WITH_WEIXIN_PAY: weixinopenid = request.session.get('openid', None) if 'micromessenger' in request.META.get('HTTP_USER_AGENT').lower( ) and not weixinopenid: #and not weixincode: api_pub = JsApi_pub() #url = api_pub.createOauthUrlForCode(reverse('weixin:usercode',args=(tmp_no,),current_app=resolve(request.path).namespace)) #url = api_pub.createOauthUrlForCode('http://eason.happydiaosi.com/weixin/getusercode') url = api_pub.createOauthUrlForCode('http://%s' % settings.SITE_DOMAIN + reverse('weixin:usercode')) return redirect(url) try: settings.SHOP_CHECKOUT_FORM_CLASS except AttributeError: pass else: from warnings import warn warn("The SHOP_CHECKOUT_FORM_CLASS setting is deprecated - please " "define your own urlpattern for the checkout_steps view, " "passing in your own form_class argument.") form_class = import_dotted_path(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) step = int( request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) 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" and request.cart.has_items(): form = form_class(request, step, initial=initial, data=data) if form.is_valid(): #human = True # 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: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: # Discount should be set before shipping, to allow # for free shipping to be first set by a discount # code. form.set_discount() try: billship_handler(request, form) tax_handler(request, form) except checkout.CheckoutError as e: checkout_errors.append(e) #wni: added for wx pay, for get order total on confirmation page #tmp_order = form.save(commit=False) #request.session['wni_wxpay_total'] = tmp_order.get_tmp_total(request) # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the initial 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 receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError as 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 = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") 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) #print type(form.errors),form.errors #form.errors.clear() if form.is_valid(): step += 1 #human = True form = form_class(request, step, initial=initial) # Update the step so that we don't rely on POST data to take us back to # the same point in the checkout process. try: request.session["order"]["step"] = step request.session.modified = True except KeyError: pass step_vars = checkout.CHECKOUT_STEPS[step - 1] template = "shop/%s.html" % step_vars["template"] context = { "CHECKOUT_STEP_FIRST": step == checkout.CHECKOUT_STEP_FIRST, "CHECKOUT_STEP_LAST": step == checkout.CHECKOUT_STEP_LAST, "step_title": step_vars["title"], "step_url": step_vars["url"], "steps": checkout.CHECKOUT_STEPS, "step": step, "form": form } return render(request, template, context)
def checkout_steps(request, form_class=OrderForm, extra_context=None): """ 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. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) try: settings.SHOP_CHECKOUT_FORM_CLASS except AttributeError: pass else: from warnings import warn warn("The SHOP_CHECKOUT_FORM_CLASS setting is deprecated - please " "define your own urlpattern for the checkout_steps view, " "passing in your own form_class argument.") form_class = import_dotted_path(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) step = int( request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) 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" and request.cart.has_items(): 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: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle discount code. This needs to # be set before shipping, to allow for free shipping to be # first set by a discount code. if step == checkout.CHECKOUT_STEP_FIRST: form.set_discount() # ALL STEPS - run billing/tax handlers. These are run on # all steps, since all fields (such as address fields) are # posted on each step, even as hidden inputs when not # visible in the current step. try: billship_handler(request, form) tax_handler(request, form) except checkout.CheckoutError as e: checkout_errors.append(e) # FINAL CHECKOUT STEP - run payment handler and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the initial 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 receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError as 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 = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") 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) # Update the step so that we don't rely on POST data to take us back to # the same point in the checkout process. try: request.session["order"]["step"] = step request.session.modified = True except KeyError: pass step_vars = checkout.CHECKOUT_STEPS[step - 1] template = "shop/%s.html" % step_vars["template"] context = { "CHECKOUT_STEP_FIRST": step == checkout.CHECKOUT_STEP_FIRST, "CHECKOUT_STEP_LAST": step == checkout.CHECKOUT_STEP_LAST, "CHECKOUT_STEP_PAYMENT": (settings.SHOP_PAYMENT_STEP_ENABLED and step == checkout.CHECKOUT_STEP_PAYMENT), "step_title": step_vars["title"], "step_url": step_vars["url"], "steps": checkout.CHECKOUT_STEPS, "step": step, "form": form } context.update(extra_context or {}) return TemplateResponse(request, template, context)
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. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) # Determine the Form class to use during the checkout process form_class = get_callable(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) step = int(request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) 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" and request.cart.has_items(): 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: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: # Discount should be set before shipping, to allow # for free shipping to be first set by a discount # code. form.set_discount() try: billship_handler(request, form) tax_handler(request, form) except checkout.CheckoutError as e: checkout_errors.append(e) # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the initial 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 receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError as 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 = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") 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) # Update the step so that we don't rely on POST data to take us back to # the same point in the checkout process. try: request.session["order"]["step"] = step request.session.modified = True except KeyError: pass step_vars = checkout.CHECKOUT_STEPS[step - 1] template = "shop/%s.html" % step_vars["template"] context = {"CHECKOUT_STEP_FIRST": step == checkout.CHECKOUT_STEP_FIRST, "CHECKOUT_STEP_LAST": step == checkout.CHECKOUT_STEP_LAST, "step_title": step_vars["title"], "step_url": step_vars["url"], "steps": checkout.CHECKOUT_STEPS, "step": step, "form": form} return render(request, template, context)
def product(request, slug, template="shop/product.html", form_class=AddProductForm, extra_context=None): """ 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) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = dumps([ dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations ]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = form_class(request.POST or None, product=product, initial=initial_data, 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) recalculate_cart(request) info(request, _("Item added to cart")) return redirect("shop_cart") 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 related = [] if settings.SHOP_USE_RELATED_PRODUCTS: related = product.related_products.published(for_user=request.user) try: # set title = membership level + product slug ("statue+gold") # discount = DiscountCode.objects.filter(title="{}+{}".format(product.sku, request.user.membership.level))[0] discount = get_or_update_discount(request, sku=product.sku) # discount_percent = (100 - discount.discount_percent)/100 discount_deduction = discount.discount_deduct except: discount_deduction = 0 try: c = CurrencyRates() hkd_rate = c.get_rate('CNY', 'HKD') except: hkd_rate = 1.1584 context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": related, "add_product_form": add_product_form, "discount": discount_deduction, "hkd_rate": hkd_rate } context.update(extra_context or {}) templates = [u"shop/%s.html" % str(product.slug), template] return TemplateResponse(request, templates, context)
def comment(request, template="generic/comments.html"): """ Handle a ``ThreadedCommentForm`` submission and redirect back to its related object. """ post_data = request.POST settings.use_editable() if settings.COMMENTS_ACCOUNT_REQUIRED: if not request.user.is_authenticated(): # Account required but user isn't authenticated - store # their post data in the session and redirect to login. request.session["unauthenticated_comment"] = post_data error(request, _("You must log in to comment. Please log in or " "sign up, and your comment will be posted.")) url = "%s?next=%s" % (settings.LOGIN_URL, reverse("comment")) return redirect(url) elif "unauthenticated_comment" in request.session: # User has logged in after post data being stored in the # session for an unauthenticated comment post, so use it. post_data = request.session.pop("unauthenticated_comment") try: model = get_model(*post_data["content_type"].split(".", 1)) obj = model.objects.get(id=post_data["object_pk"]) except (KeyError, TypeError, AttributeError, ObjectDoesNotExist): # Something was missing from the post so abort. return HttpResponseRedirect("/") form = ThreadedCommentForm(request, obj, post_data) if form.is_valid(): url = obj.get_absolute_url() if is_spam(request, form, url): return redirect(url) comment = form.get_comment_object() if request.user.is_authenticated(): comment.user = request.user comment.by_author = request.user == getattr(obj, "user", None) comment.ip_address = request.META.get("HTTP_X_FORWARDED_FOR", request.META["REMOTE_ADDR"]) comment.replied_to_id = post_data.get("replied_to") comment.save() comment_was_posted.send(sender=comment.__class__, comment=comment, request=request) # Send notification emails. comment_url = add_cache_bypass(comment.get_absolute_url()) #======================================================================= # send email to reply or post people,instead of ADMINS #======================================================================= try: from mezzanine.blog.models import BlogPost notify_emails = [BlogPost.objects.get(id=comment.object_pk).user.email] if comment.threadedcomment.replied_to != None: other_email = comment.threadedcomment.replied_to.user_email notify_emails += [other_email] # print notify_emails except: notify_emails = filter(None, [addr.strip() for addr in settings.COMMENTS_NOTIFICATION_EMAILS.split(",")]) if notify_emails: subject = _("New comment for: ") + unicode(obj) context = { "comment": comment, "comment_url": comment_url, "request": request, "obj": obj, } send_mail_template(subject, "email/comment_notification", settings.DEFAULT_FROM_EMAIL, notify_emails, context, fail_silently=settings.DEBUG) response = HttpResponseRedirect(comment_url) # Store commenter's details in a cookie for 90 days. cookie_expires = 60 * 60 * 24 * 90 for field in ThreadedCommentForm.cookie_fields: cookie_name = ThreadedCommentForm.cookie_prefix + field cookie_value = post_data.get(field, "") set_cookie(response, cookie_name, cookie_value, cookie_expires) return response else: # Show errors with stand-alone comment form. context = {"obj": obj, "posted_comment_form": form} return render(request, template, context)
def 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. """ address = request.session['address'] if 'cart loaded' in request.session: current_store = request.session['stores'][0] else: current_store = [] published_products = Product.objects.published(for_user=request.user) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = simplejson.dumps([dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = AddProductForm(request.POST or None, product=product, initial=initial_data, to_cart=to_cart) if request.method == "POST": if add_product_form.is_valid(): if to_cart: if 'cart loaded' in request.session: current_store = Store.objects.filter(name__exact=product.store)[0] if current_store != request.session['stores'][0]: info(request, _("Sorry, the item cannot be added to your cart. " "By NY law you cannot shop from two different liquor stores simultaneously.")) return HttpResponseRedirect('/shop/') else: request.session['cart loaded'] = 'cart loaded' store = Store.objects.filter(name__exact=product.store) request.session['stores'] = store request.session['delivery min'] = store[0].delivery_min current_store = store[0] name = unicodedata.normalize('NFKD', current_store.name).encode('ascii','ignore') store_slug = '/shop/'+slugify(name)+'/' request.session['store slug'] = store_slug quantity = add_product_form.cleaned_data["quantity"] request.cart.add_item(add_product_form.variation, quantity) recalculate_cart(request) info(request, _("Item added to cart. Anything else from %s?" % name )) # return redirect("shop_cart") return redirect(store_slug) 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 context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": product.related_products.published( for_user=request.user), "add_product_form": add_product_form, "address": address, "stores": current_store, } templates = [u"shop/%s.html" % unicode(product.slug), template] # new return render(request, templates, context)
def 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) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = simplejson.dumps([dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations]) to_cart = (request.method == "POST" and request.POST.get("add_cart") is not None) save_product = (request.method == "POST" and request.POST.get("save_product") is not None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 quote = None if product.custom_product: quote_id = request.GET.get('quote_id') if quote_id: quote = get_object_or_404(Quote, pk=quote_id) add_product_form = AddCustomProductForm(request.POST or None, product=product, initial=initial_data, to_cart=to_cart, quote=quote) else: add_product_form = AddProductForm(request.POST or None, product=product, initial=initial_data, to_cart=to_cart) if request.method == "POST": if add_product_form.is_valid(): if save_product: user_catagory = Category.objects.get(pk=15) new_product = product new_images = product.images.all() new_variations = variations for i in new_images: i.pk = None i.id = None i.save() message = add_product_form.cleaned_data["message"] flat_message = message.replace('\n', ' ') new_product.pk = None new_product.id = None new_product.sku = None new_product.title = trunc(s=flat_message).title() + " Canvas Print" new_product.slug = None new_product.custom_product = False #new_product.available = False new_product.content = new_product.content +flat_message new_product.save() new_product.categories.add(user_catagory) new_product.images = new_images data_uri = add_product_form.cleaned_data["image_data"] img_str = re.search(r'base64,(.*)', data_uri).group(1) temp_img = img_str.decode('base64') image = ProductImage(file=ContentFile(temp_img, new_product.slug+'.png'), description = message, product=new_product) image.save() for v in new_variations: v.pk = None v.id = None v.sku = None v.image = image v.save() new_product.variations = new_variations new_product.copy_default_variation() json = add_product_form.cleaned_data["json_data"] custom_product = CustomProduct(product = new_product, text = message, quote=quote, json=json) custom_product.save() return redirect("shop_product", slug=new_product.slug) elif to_cart: quantity = add_product_form.cleaned_data["quantity"] request.cart.add_item(add_product_form.variation, quantity) recalculate_cart(request) info(request, _("Item added to cart")) return redirect("shop_cart") 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 context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": product.related_products.published( for_user=request.user), "add_product_form": add_product_form } templates = [u"shop/%s.html" % unicode(product.slug), template] return render(request, templates, context)
def write_review(request, content_type_id, object_id, template="generic/includes/write_review.html"): store = request.GET.get('store', 'None') parent = None if store != 'None': store = store.lower() try: parent = BlogPost.objects.get(title__iexact=store) content_type_id = ContentType.objects.get_for_model(parent).pk object_id = parent.pk except: pass if not parent: ctype = get_object_or_404(ContentType, pk=content_type_id) parent = get_object_or_404(ctype.model_class(), pk=object_id) prefix = "write_review" if request.method == 'POST': response = initial_validation_review(request, prefix, content_type_id, object_id, store) if isinstance(response, HttpResponse): return response obj, post_data = response form = ReviewForm(request, obj, request.POST) if form.is_valid() and request.user.is_authenticated(): url = obj.get_absolute_url() if is_spam(request, form, url): return redirect(url) comment = form.save(request) """ Send activity feed to those who follow this vendor page. """ if request.user.is_authenticated(): action.send(obj, verb=settings.GOT_REVIEW_VERB, target=comment ) if request.is_ajax(): html = render_to_string('generic/includes/comment_ajax.html', { 'comment': comment, 'request':request }) res = {'html': html, 'store': obj.title, 'success':True} response = HttpResponse( simplejson.dumps(res), 'application/json' ) # Store commenter's details in a cookie for 90 days. for field in ReviewForm.cookie_fields: cookie_name = ReviewForm.cookie_prefix + field cookie_value = post_data.get(field, "") set_cookie(response, cookie_name, cookie_value) return response else: response = redirect(add_cache_bypass(comment.get_absolute_url())) return response elif request.is_ajax() and form.errors: return HttpResponse( simplejson.dumps({"errors": form.errors, "success":False}), 'application/json') else: post_data = None posted_session_key = "unauthenticated_" + prefix post_session_generic_review_store_key = "unauthenticated_store_" + prefix if posted_session_key in request.session: post_data = request.session.pop(posted_session_key) form = ReviewForm(request, parent, post_data) if post_session_generic_review_store_key in request.session: request.session.pop(post_session_generic_review_store_key) else: form = ReviewForm(request, parent) form.fields['overall_value'].widget = forms.HiddenInput() form.fields['price_value'].widget = forms.HiddenInput() form.fields['website_ex_value'].widget = forms.HiddenInput() form.fields['quality_value'].widget = forms.HiddenInput() form.fields['service_value'].widget = forms.HiddenInput() form.fields['exchange_value'].widget = forms.HiddenInput() action_url = reverse("write_review", kwargs={ 'content_type_id':content_type_id, 'object_id':object_id }) if store != 'None': action_url += '?store=' + store context = {"new_review":True, "obj": parent, "posted_comment_form": form, "action_url": action_url } response = render(request, template, context) return response
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. authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("shop_checkout")) return redirect(url) # Determine the Form class to use during the checkout process form_class = get_callable(settings.SHOP_CHECKOUT_FORM_CLASS) initial = checkout.initial_order_data(request, form_class) step = int( request.POST.get("step", None) or initial.get("step", None) or checkout.CHECKOUT_STEP_FIRST) 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" and request.cart.has_items(): 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: if field in request.session["order"]: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: try: billship_handler(request, form) tax_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 initial 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 receipt email. order = form.save(commit=False) order.setup(request) # Try payment. try: 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 = redirect("shop_complete") if form.cleaned_data.get("remember"): remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") 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)
# External payment management #=========================================================================== context['CHECKOUT_STEP_PAYMENT'] = step == checkout.CHECKOUT_STEP_PAYMENT if step == checkout.CHECKOUT_STEP_PAYMENT: form = form_class(request, step, initial=initial, data=data) order = form.save(commit=False) order.setup(request) context['start_payment_form'] = provider.get_start_payment_form(request, order) response = render(request, template, context) if step == checkout.CHECKOUT_STEP_PAYMENT: # Set the cookie for remembering address details # if the "remember" checkbox was checked. 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") return response def finalize_order(request): '''Helper function that actually complete the order when the payment provider tells us so. ''' order_id = provider.get_order_id(request) order = Order.objects.get(pk=order_id) #Order is already completed if order.payment_done: return
def product(request, slug, template="shop/product.html", form_class=AddProductForm): """ 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) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = dumps([ dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations ]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = form_class(request.POST or None, product=product, initial=initial_data, 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) recalculate_cart(request) info(request, _("Item added to cart")) return redirect(request.path) 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 related = [] if settings.SHOP_USE_RELATED_PRODUCTS: related = product.related_products.published(for_user=request.user) context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": related, "add_product_form": add_product_form, "categories": product.categories.all()[0].get_ascendants()[::-1] + [product.categories.all()[0]] } # templates = [u"shop/%s.html" % str(product.slug), template] templates = [] # Check for a template matching the page's content model. if product.content_model is not None and product.content_model != 'product': templates.append(u"shop/products/%s.html" % product.content_model) context["characteristics"] = product.get_content_model( ).get_characteristics() if product.content_model in ('productportal', 'productfacing'): context["suitable_hearth"] = product.get_content_model( ).suitable_hearth.published(for_user=request.user) context["suitable_topka"] = product.get_content_model( ).suitable_topka.published(for_user=request.user) if product.content_model in ('producthearth', 'producttopka'): context["suitable_faces"] = product.get_content_model( ).suitable_faces.published(for_user=request.user) context["suitable_portals"] = product.get_content_model( ).suitable_portals.published(for_user=request.user) templates.append(template) return render(request, templates, context)
def 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) product = get_object_or_404(published_products, slug=slug) if not request.is_ajax(): page = Category.objects.get(slug__exact='shop') products = Product.objects.published(for_user=request.user ).filter(page.category.filters()).distinct() sort_options = [(slugify(option[0]), option[1]) for option in settings.SHOP_PRODUCT_SORT_OPTIONS] sort_by = request.GET.get("sort", sort_options[0][1]) products = paginate(products.order_by(sort_by), request.GET.get("page", 1), settings.SHOP_PER_PAGE_CATEGORY, settings.MAX_PAGING_LINKS) products.sort_by = sort_by sub_categories = page.category.children.published() child_categories = Category.objects.filter(id__in=sub_categories) context = RequestContext(request, locals()) return render_to_response('pages/category.html', {}, context_instance=context) else: fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = simplejson.dumps([dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = AddProductForm(request.POST or None, product=product, initial=initial_data, 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) recalculate_cart(request) return HttpResponse(request.cart.total_quantity()) 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 context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": product.related_products.published( for_user=request.user), "add_product_form": add_product_form } templates = [u"shop/%s.html" % unicode(product.slug), template] return render(request, templates, context)
def product(request, slug, template="shop/product.html", form_class=AddProductForm): """ 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) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = dumps([dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = form_class(request.POST or None, product=product, initial=initial_data, 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) recalculate_cart(request) info(request, _("Item added to cart")) return redirect(request.path) 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 related = [] if settings.SHOP_USE_RELATED_PRODUCTS: related = product.related_products.published(for_user=request.user) context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": related, "add_product_form": add_product_form, "categories": product.categories.all()[0].get_ascendants()[::-1] + [product.categories.all()[0]] } # templates = [u"shop/%s.html" % str(product.slug), template] templates = [] # Check for a template matching the page's content model. if product.content_model is not None and product.content_model != 'product': templates.append(u"shop/products/%s.html" % product.content_model) context["characteristics"] = product.get_content_model().get_characteristics() if product.content_model in ('productportal', 'productfacing'): context["suitable_hearth"] = product.get_content_model().suitable_hearth.published(for_user=request.user) context["suitable_topka"] = product.get_content_model().suitable_topka.published(for_user=request.user) if product.content_model in ('producthearth', 'producttopka'): context["suitable_faces"] = product.get_content_model().suitable_faces.published(for_user=request.user) context["suitable_portals"] = product.get_content_model().suitable_portals.published(for_user=request.user) templates.append(template) return render(request, templates, context)
def product(request, slug, template="shop/product.html", form_class=AddProductForm, extra_context=None): print "MODIFIED DEF PRODUCT" """ 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) product = get_object_or_404(published_products, slug=slug) fields = [f.name for f in ProductVariation.option_fields()] variations = product.variations.all() variations_json = dumps([ dict([(f, getattr(v, f)) for f in fields + ["sku", "image_id"]]) for v in variations ]) to_cart = (request.method == "POST" and request.POST.get("add_wishlist") is None) initial_data = {} if variations: initial_data = dict([(f, getattr(variations[0], f)) for f in fields]) initial_data["quantity"] = 1 add_product_form = form_class(request.POST or None, product=product, initial=initial_data, to_cart=to_cart) if request.method == "POST": if add_product_form.is_valid(): if to_cart: quantity = add_product_form.cleaned_data["quantity"] data = add_product_form.cleaned_data data = dict(data) request.session['quantity'] = json.dumps(data['quantity']) request.session['fabrics'] = str(data['fabrics']) request.session['sku'] = str(add_product_form.variation.sku) #checking what data/fields are stored in request.session before redirecting to other steps # for field in request.session.iteritems(): # print "FIRST FIELD ITEM IS " + str(field) #redirect to step 2. "tailorSelect" calls the next view and is configured in the monkeyPatch/urls.py return HttpResponseRedirect("tailorSelect") 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 related = [] ### # fabrics = product.fabrics.all() if settings.SHOP_USE_RELATED_PRODUCTS: related = product.related_products.published(for_user=request.user) context = { "product": product, "editable_obj": product, "images": product.images.all(), "variations": variations, "variations_json": variations_json, "has_available_variations": any([v.has_price() for v in variations]), "related_products": related, "add_product_form": add_product_form, } context.update(extra_context or {}) templates = [u"shop/%s.html" % str(product.slug), template] return render(request, templates, context)
def wishlist(request, template="shop/wishlist1.html"): """ Display the wishlist and handle removing items from the wishlist and adding them to the cart. """ if not settings.SHOP_USE_WISHLIST: raise Http404 skus = request.wishlist error = None if request.method == "POST": print request.POST print "nihao" to_cart = request.POST.get("add_cart") print len(to_cart) print "to_cart:"+to_cart #{u'sku': [u'28'], u'csrfmiddlewaretoken': [u'P5IBTacZNNoP6QzaVPMScIdje3cGBEbv'], u'add_cart': [u'Buy'], u'quantity': [u'1']}> # test={u'sku': [u'28'], u'csrfmiddlewaretoken': [u'P5IBTacZNNoP6QzaVPMScIdje3cGBEbv'], u'add_cart': [u'Buy'], u'quantity': [u'1']} # add_product_form = AddProductForm(test or None, # to_cart=to_cart) # # print request.POST # print add_product_form if len(to_cart)>10: pass tmp_post=request.POST.copy() wish_skus=tmp_post.getlist("sku") if wish_skus=="none": message = _("error in wishlist") # print "wish_skus:" + wish_skus for i in wish_skus: tmp_post.__setitem__("sku",i) add_product_form = AddProductForm(tmp_post or None, to_cart=to_cart) if add_product_form.is_valid(): request.cart.add_item(add_product_form.variation, 1) recalculate_cart(request) else: error = list(add_product_form.errors.values())[0] # print "error:"+str(skus) skus.remove(i) message = _("Items added to cart") url = "shop_cart" elif to_cart: add_product_form = AddProductForm(request.POST or None, to_cart=to_cart) if add_product_form.is_valid(): request.cart.add_item(add_product_form.variation, 1) print add_product_form.variation recalculate_cart(request) message = _("Item added to cart") url = "shop_cart" else: error = list(add_product_form.errors.values())[0] else: add_product_form = AddProductForm(request.POST or None, to_cart=to_cart) message = _("Item removed from wishlist") url = "shop_wishlist" sku = request.POST.get("sku") print request.POST.get("sku") print skus if sku in skus: skus.remove(sku) if not error: info(request, message) response = redirect(url) set_cookie(response, "wishlist", ",".join(skus)) return response # Remove skus from the cookie that no longer exist. published_products = Product.objects.published(for_user=request.user) f = {"product__in": published_products, "sku__in": skus} wishlist = ProductVariation.objects.filter(**f).select_related(depth=1) wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku)) context = {"wishlist_items": wishlist, "error": error} response = render(request, template, context) if len(wishlist) < len(skus): skus = [variation.sku for variation in wishlist] set_cookie(response, "wishlist", ",".join(skus)) return response