Ejemplo n.º 1
0
def cart(request, template="shop/cart.html"):
    """
    Display cart and handle removing items from the cart.
    """
    cart_formset = CartItemFormSet(instance=request.cart)
    discount_form = DiscountForm(request, request.POST or None)
    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"))
        else:
            valid = discount_form.is_valid()
            if valid:
                discount_form.set_discount()
        if valid:
            return HttpResponseRedirect(reverse("shop_cart"))
    context = {"cart_formset": cart_formset}
    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))
Ejemplo n.º 2
0
def account(request, template="shop/account.html"):
    """
    Display and handle both the login and signup forms.
    """
    login_form = LoginForm()
    signup_form = SignupForm()
    if request.method == "POST":
        posted_form = None
        message = ""
        if request.POST.get("login") is not None:
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                posted_form = login_form
                message = _("Successfully logged in")
        else:
            signup_form = SignupForm(request.POST)
            if signup_form.is_valid():
                signup_form.save()
                posted_form = signup_form
                message = _("Successfully signed up")
        if posted_form is not None:
            posted_form.login(request)
            info(request, message, fail_silently=True)
            return HttpResponseRedirect(request.GET.get("next", "/"))
    context = {"login_form": login_form, "signup_form": signup_form}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 3
0
def blog_post_list(request, tag=None, year=None, month=None, username=None,
    category=None, template="blog/blog_post_list.html"):
    """
    Display a list of blog posts.
    """
    settings.use_editable()
    blog_posts = BlogPost.objects.published(for_user=request.user)
    if tag is not None:
        tag = get_object_or_404(Keyword, slug=tag)
        blog_posts = blog_posts.filter(keywords=tag)
    if year is not None:
        blog_posts = blog_posts.filter(publish_date__year=year)
        if month is not None:
            blog_posts = blog_posts.filter(publish_date__month=month)
            month = month_name[int(month)]
    if category is not None:
        category = get_object_or_404(BlogCategory, slug=category)
        blog_posts = blog_posts.filter(categories=category)
    author = None
    if username is not None:
        author = get_object_or_404(User, username=username)
        blog_posts = blog_posts.filter(user=author)
    blog_posts = paginate(blog_posts, request.GET.get("page", 1),
        settings.BLOG_POST_PER_PAGE,
        settings.BLOG_POST_MAX_PAGING_LINKS)
    context = {"blog_posts": blog_posts, "year": year, "month": month,
               "tag": tag, "category": category, "author": author,
               "use_disqus": bool(settings.COMMENTS_DISQUS_SHORTNAME),
               "blog_page": blog_page()}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 4
0
def cart(request, template="shop/cart.html"):
    """
    Display cart and handle removing items from the cart.
    """
    if request.method == "POST":
        cart = Cart.objects.from_request(request)
        cart.remove_item(request.POST.get("item_id"))
        info(request, _("Item removed from cart"), fail_silently=True)
        return HttpResponseRedirect(reverse("shop_cart"))
    return render_to_response(template, {}, RequestContext(request))
Ejemplo n.º 5
0
def search(request, template="shop/search_results.html"):
    """
    Display product search results.
    """
    settings.use_editable()
    query = request.REQUEST.get("query", "")
    results = Product.objects.published_for(user=request.user).search(query)
    results = product_list(results, request, settings.SHOP_PER_PAGE_SEARCH)
    context = {"query": query, "results": results}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 6
0
def search(request, template="search_results.html"):
    """
    Display search results.
    """
    settings.use_editable()
    query = request.GET.get("q", "")
    results = Displayable.objects.search(query)
    results = paginate(results, request.GET.get("page", 1), 
        settings.SEARCH_PER_PAGE, settings.SEARCH_MAX_PAGING_LINKS)
    context = {"query": query, "results": results}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 7
0
def direct_to_template(request, template, extra_context=None, **kwargs):
    """
    Replacement for Django's ``direct_to_template`` that uses Mezzanine's 
    device-aware ``render_to_response``.
    """
    context = extra_context or {}
    context["params"] = kwargs
    for (key, value) in context.items():
        if callable(value):
            context[key] = value()
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 8
0
def news_post_list(request, template="news/news_post_list.html"):
    """
    Display a list of news posts.
    """
    settings.use_editable()
    news_posts = NewsPost.objects.published(for_user=request.user)
    author = None
    news_posts = paginate(news_posts, request.GET.get("page", 1),
        settings.NEWS_PER_PAGE,
        settings.NEWS_POST_MAX_PAGING_LINKS)
    context = {"news_posts": news_posts, "news_page": news_page()}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 9
0
def search(request, template="search_results.html"):
    """
    Display search results.
    """
    settings.use_editable()
    query = request.GET.get("q", "")
    results = Displayable.objects.search(query)
    results = paginate(results, request.GET.get("page", 1),
                       settings.SEARCH_PER_PAGE,
                       settings.SEARCH_MAX_PAGING_LINKS)
    context = {"query": query, "results": results}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 10
0
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)
    AddProductForm = get_add_product_form(product)
    add_product_form = AddProductForm(initial={"quantity": 1})
    if request.method == "POST":
        to_cart = request.POST.get("add_wishlist") is None
        add_product_form = AddProductForm(request.POST, to_cart=to_cart)
        if add_product_form.is_valid():
            if to_cart:
                Cart.objects.from_request(request).add_item(
                    add_product_form.variation,
                    add_product_form.cleaned_data["quantity"])
                info(request, _("Item added to cart"), fail_silently=True)
                return HttpResponseRedirect(reverse("shop_cart"))
            else:
                skus = request.COOKIES.get("wishlist", "").split(",")
                sku = add_product_form.variation.sku
                if sku not in skus:
                    skus.append(sku)
                info(request, _("Item added to wishlist"), fail_silently=True)
                response = HttpResponseRedirect(reverse("shop_wishlist"))
                set_cookie(response, "wishlist", ",".join(skus))
                return response
    # Build variations JSON from list of variation dicts.
    fields = [f.name for f in ProductVariation.option_fields()]
    fields.extend(["sku", "image_id"])
    variations = []
    variations_json = []
    has_available_variations = False
    for variation in product.variations.all():
        if not has_available_variations and variation.has_price():
            has_available_variations = True
        variations.append(variation)
        variation_dict = dict([(f, getattr(variation, f)) for f in fields])
        variations_json.append(variation_dict)
    variations_json = simplejson.dumps(variations_json)
    related = product.related_products.published(for_user=request.user)
    context = {"product": product, "images": list(product.images.all()),
               "variations": variations, "variations_json": variations_json,
               "has_available_variations": has_available_variations,
               "related_products": list(related),
               "add_product_form": add_product_form}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 11
0
def wishlist(request, template="shop/wishlist.html"):
    """
    Display the wishlist and handle removing items from the wishlist and
    adding them to the cart.
    """

    skus = request.COOKIES.get("wishlist", "").split(",")
    error = None
    if request.method == "POST":
        sku = request.POST.get("sku")
        to_cart = request.POST.get("add_cart") is not None
        if to_cart:
            quantity = 1
            try:
                variation = ProductVariation.objects.get(sku=sku)
            except ProductVariation:
                error = _("This item is no longer available")
            else:
                if not variation.has_stock(quantity):
                    error = _("This item is currently out of stock")
                else:
                    cart = Cart.objects.from_request(request)
                    cart.add_item(variation, quantity)
        if error is None:
            if sku in skus:
                skus.remove(sku)
            if to_cart:
                message = _("Item added to cart")
                response = HttpResponseRedirect(reverse("shop_cart"))
            else:
                message = _("Item removed from wishlist")
                response = HttpResponseRedirect(reverse("shop_wishlist"))
            info(request, message, fail_silently=True)
            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": wishlist, "error": error}
    response = render_to_response(template, context, RequestContext(request))
    if len(wishlist) < len(skus):
        skus = [variation.sku for variation in wishlist]
        set_cookie(response, "wishlist", ",".join(skus))
    return response
Ejemplo n.º 12
0
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)
    to_cart = (request.method == "POST"
               and request.POST.get("add_wishlist") is None)
    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)
                recalculate_discount(request)
                info(request, _("Item added to cart"))
                return HttpResponseRedirect(reverse("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 = HttpResponseRedirect(reverse("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])
    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
    }
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 13
0
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)
    to_cart = (request.method == "POST" and
               request.POST.get("add_wishlist") is None)
    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)
                recalculate_discount(request)
                info(request, _("Item added to cart"))
                return HttpResponseRedirect(reverse("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 = HttpResponseRedirect(reverse("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])
    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
    }
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 14
0
def complete(request, template="shop/complete.html"):
    """
    Redirected to once an order is complete - pass the order object
    for tracking items via Google Anayltics, and displaying in
    the template if required.
    """
    order = Order.objects.from_request(request)
    items = order.items.all()
    # Assign product names to each of the items since they're not
    # stored.
    skus = [item.sku for item in items]
    variations = ProductVariation.objects.filter(sku__in=skus)
    names = {}
    for variation in variations.select_related(depth=1):
        names[variation.sku] = variation.product.title
    for i, item in enumerate(items):
        setattr(items[i], "name", names[item.sku])
    context = {"order": order, "items": items}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 15
0
def wishlist(request, template="shop/wishlist.html"):
    """
    Display the wishlist and handle removing items from the wishlist and
    adding them to the cart.
    """

    skus = request.wishlist
    error = None
    if request.method == "POST":
        to_cart = request.POST.get("add_cart")
        add_product_form = AddProductForm(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_discount(request)
                message = _("Item added to cart")
                url = reverse("shop_cart")
            else:
                error = add_product_form.errors.values()[0]
        else:
            message = _("Item removed from wishlist")
            url = reverse("shop_wishlist")
        sku = request.POST.get("sku")
        if sku in skus:
            skus.remove(sku)
        if not error:
            info(request, message)
            response = HttpResponseRedirect(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_to_response(template, context, RequestContext(request))
    if len(wishlist) < len(skus):
        skus = [variation.sku for variation in wishlist]
        set_cookie(response, "wishlist", ",".join(skus))
    return response
Ejemplo n.º 16
0
def wishlist(request, template="shop/wishlist.html"):
    """
    Display the wishlist and handle removing items from the wishlist and
    adding them to the cart.
    """

    skus = request.wishlist
    error = None
    if request.method == "POST":
        to_cart = request.POST.get("add_cart")
        add_product_form = AddProductForm(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_discount(request)
                message = _("Item added to cart")
                url = reverse("shop_cart")
            else:
                error = add_product_form.errors.values()[0]
        else:
            message = _("Item removed from wishlist")
            url = reverse("shop_wishlist")
        sku = request.POST.get("sku")
        if sku in skus:
            skus.remove(sku)
        if not error:
            info(request, message)
            response = HttpResponseRedirect(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_to_response(template, context, RequestContext(request))
    if len(wishlist) < len(skus):
        skus = [variation.sku for variation in wishlist]
        set_cookie(response, "wishlist", ",".join(skus))
    return response
Ejemplo n.º 17
0
def cart(request, template="shop/cart.html"):
    """
    Display cart and handle removing items from the cart.
    """
    discount_form = DiscountForm(request, request.POST or None)
    if request.method == "POST":
        remove_sku = request.POST.get("item_id")
        if remove_sku:
            cart = Cart.objects.from_request(request)
            cart.remove_item(remove_sku)
            info(request, _("Item removed from cart"), fail_silently=True)
        elif discount_form.is_valid():
            discount_form.set_discount()
        return HttpResponseRedirect(reverse("shop_cart"))
    context = {}
    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))
Ejemplo n.º 18
0
def complete(request, template="shop/complete.html"):
    """
    Redirected to once an order is complete - pass the order object
    for tracking items via Google Anayltics, and displaying in
    the template if required.
    """
    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        raise Http404
    items = order.items.all()
    # Assign product names to each of the items since they're not
    # stored.
    skus = [item.sku for item in items]
    variations = ProductVariation.objects.filter(sku__in=skus)
    names = {}
    for variation in variations.select_related(depth=1):
        names[variation.sku] = variation.product.title
    for i, item in enumerate(items):
        setattr(items[i], "name", names[item.sku])
    context = {"order": order, "items": items}
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 19
0
            # 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 = OrderForm(request, step, initial=initial, data=data,
                             errors=checkout_errors)
            if form.is_valid():
                step += 1
                form = OrderForm(request, step, initial=initial)

    step_vars = checkout.CHECKOUT_STEPS[step - 1]
    template = "shop/%s.html" % step_vars["template"]
    CHECKOUT_STEP_FIRST = step == checkout.CHECKOUT_STEP_FIRST
    context = {"form": form, "CHECKOUT_STEP_FIRST": CHECKOUT_STEP_FIRST,
               "step_title": step_vars["title"], "step_url": step_vars["url"],
               "steps": checkout.CHECKOUT_STEPS, "step": step}
    return render_to_response(template, context, RequestContext(request))


def complete(request, template="shop/complete.html"):
    """
    Redirected to once an order is complete - pass the order object
    for tracking items via Google Anayltics, and displaying in
    the template if required.
    """
    order = Order.objects.from_request(request)
    items = order.items.all()
    # Assign product names to each of the items since they're not
    # stored.
    skus = [item.sku for item in items]
    variations = ProductVariation.objects.filter(sku__in=skus)
    names = {}
Ejemplo n.º 20
0
            if form.is_valid():
                step += 1
                form = form_class(request, step, initial=initial)

    step_vars = checkout.CHECKOUT_STEPS[step - 1]
    template = "shop/%s.html" % step_vars["template"]
    CHECKOUT_STEP_FIRST = step == checkout.CHECKOUT_STEP_FIRST
    context = {
        "form": form,
        "CHECKOUT_STEP_FIRST": CHECKOUT_STEP_FIRST,
        "step_title": step_vars["title"],
        "step_url": step_vars["url"],
        "steps": checkout.CHECKOUT_STEPS,
        "step": step
    }
    return render_to_response(template, context, RequestContext(request))


def complete(request, template="shop/complete.html"):
    """
    Redirected to once an order is complete - pass the order object
    for tracking items via Google Anayltics, and displaying in
    the template if required.
    """
    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        raise Http404
    items = order.items.all()
    # Assign product names to each of the items since they're not
    # stored.