Beispiel #1
0
def contact_form_submit(request, xhr=None):

    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            from emailer.views import _admin_notify_contact

            _admin_notify_contact(form.cleaned_data)
            return _render(request, "shop/forms/contact_form_thanks.html", locals())
        else:
            page = get_object_or_404(Page, slug="contact-us")
            return _render(request, "shop/forms/contact_form.html", locals())

    url = reverse("page", args=["contact-us"])
    return HttpResponseRedirect(url)
Beispiel #2
0
def review_order(request, hash):

    order = get_object_or_404(Order, hashkey=hash)

    if request.method == "POST":

        form = ReviewOrderForm(request.POST)
        if form.is_valid():
            words = form.cleaned_data["words"]
            product = get_object_or_404(Product, pk=form.cleaned_data["product"])
            first_name = order.owner.first_name
            last_name = order.owner.last_name
            email = order.owner.email
            review = Review.objects.create(
                text=words,
                product=product,
                first_name=first_name,
                last_name=last_name,
                email=email,
                date_submitted=datetime.now(),
            )

            review.save()

            if request.is_ajax():
                data = {"words": words}
                json = simplejson.dumps(data, cls=DjangoJSONEncoder)
                return HttpResponse(json)

            else:
                pass

    return _render(request, "shop/forms/review_order_form.html", locals())
Beispiel #3
0
def email_signup(request):
    if request.method == "POST":
        form = EmailSignupForm(request.POST)
        if form.is_valid():

            try:
                existing_signup = get_object_or_404(Subscriber, email=form.cleaned_data["email"])
                message = _(
                    "<h3>Looks like you're already signed up! You don't need to do anything else, and you'll receive TEAMails as normal.</h3>"
                )
            except:
                new_signup = Subscriber.objects.create(
                    email=form.cleaned_data["email"],
                    date_signed_up=datetime.now(),
                    language=get_language(),
                    confirmed=True,  # TODO - change this so that an email gets sent off immediately asking them to confirm
                )
                new_signup.save()
                message = _(
                    "<h3>Awesome! You're now signed up to receive TEAMails - they're roughly fortnightly, and you can unsubscribe at any time by clicking the link in the email.</h3>"
                )

            if request.is_ajax():
                return HttpResponse(message)

            else:
                return _render(request, "shop/emails/signup_confirmed.html", locals())

    else:
        form = EmailSignupForm()

    url = request.META.get("HTTP_REFERER", "/")
    return HttpResponseRedirect(url)
Beispiel #4
0
def index(request):
    objects = BlogEntry.objects.filter(
            is_draft=False, 
            title__isnull=False
        ).exclude(
            title__exact="None"
        ).order_by('-date_added')
    
    if request.GET.get('tag'):
        tag = request.GET.get('tag')
        objects = objects.filter(tags__name__in=[tag])
      
    try:
        p = int(request.GET.get('page', '1'))
    except ValueError:
        p = 1
    
    paginator = Paginator(objects, 10) 
    # If page request (9999) is out of range, deliver last page of results.
    try:
        entries = paginator.page(p)
    except (EmptyPage, InvalidPage):
        entries = paginator.page(paginator.num_pages)
    
    teas = _get_products(request, random=True)[:2]
                       
    return _render(request, "blog/home.html", locals())
Beispiel #5
0
def admin_product(request, id):
    product = get_object_or_404(Product, pk=id)
    
    sold_items = WarehouseItem.objects.filter(
        unique_product__parent_product=product,
        sold__isnull=False,
        )
        
    total_weight = 0
    for x in sold_items:
        total_weight += x.unique_product.weight
    
    start_date = (datetime.now() - timedelta(weeks=52))
    end_date = datetime.now()
    sold_this_year = WarehouseItem.objects.filter(
        unique_product__parent_product=product,
        sold__range=(start_date, end_date),
        )
        
    in_stock = WarehouseItem.objects.filter(
        unique_product__parent_product=product,
        sold__isnull=True,
        )
    
    
    
    

    # if there's a date range, filter by date range.            
                
    return _render(request, 'my_admin/product.html', locals())
Beispiel #6
0
def orders(request, **kwargs):
    
    if request.GET.get('w'):
        weeks = int(request.GET['w'])
    else:
        weeks = 4
        
    start_date = (datetime.now() - timedelta(weeks=weeks))
    end_date = datetime.now()     
       
    
    if request.GET.get('unpaid'):
        unpaid = True
        packages = Order.objects.filter(
            date_paid__isnull=True, 
            date_confirmed__range=(start_date, end_date)
        ).order_by('-date_confirmed')
    else:
        packages = CustomerPackage.objects.filter(
            created__range=(start_date, end_date), 
            **kwargs
        ).order_by('-created')  
        
        
    return _render(request, 'my_admin/orders.html', locals())
Beispiel #7
0
def index(request):
    packages = CustomerPackage.objects.filter(postage_cost=None, shipping_due_date__isnull=True).order_by('-created')
    
    today = datetime.today()
    next_week = (datetime.today() + timedelta(weeks=5))
    
    monthly_packages = CustomerPackage.objects.filter(shipping_due_date__range=(today, next_week), posted__isnull=True).order_by('-created')
    
    return _render(request, "my_admin/home.html", locals())
Beispiel #8
0
def order_confirm(request):

    try:
        order = get_object_or_404(Order, id=request.session["ORDER_ID"])
    except:
        problem = _("You don't have any items in your basket, so you can't process an order!")
        return _render(request, "shop/order-problem.html", locals())

    shopper = order.owner
    order.basket = Basket.objects.get(id=request.session["BASKET_ID"])
    order.save()

    basket = _get_basket_value(request)

    amount_in_cents = int(float(basket["total_price"]) * 100)  # for stupid stripe...

    # THIS HANDLES STRIPE
    if request.method == "POST":

        stripe.api_key = settings.STRIPE_SECRET_KEY
        token = request.POST["stripeToken"]

        try:
            charge = stripe.Charge.create(
                amount=amount_in_cents,
                currency=basket["currency"].code.lower(),
                card=token,
                description=order.owner.user.email,
            )

            # UPDATE THE ORDER DETAILS
            order.status = Order.STATUS_PAID
            order.date_paid = datetime.now()
            order.save()

            # IF THERE WAS A SINGLE USE DISCOUNT, UPDATE IT
            if order.discount:
                if order.discount.single_use == True:
                    order.discount.is_active = False
                    order.discount.save()

            from emailer.views import _payment_success

            _payment_success(order)

            # NOW CREATE A CUSTOMER PACKAGE
            from logistics.views import _create_customer_package

            _create_customer_package(order)

            return HttpResponseRedirect(reverse("order_complete", args=[order.hashkey]))
        except stripe.CardError, e:

            # do we need to do something here like show an error message?!

            pass
Beispiel #9
0
def sale(request):
    category = get_object_or_404(Category, slug=_("sale"))
    ups = UniqueProduct.objects.filter(is_active=True, sale_price__isnull=False, currency=_get_currency(request))
    products = []
    for x in ups:
        p = x.parent_product
        p.price = x
        products.append(p)

    return _render(request, "shop/category.html", locals())
Beispiel #10
0
def stocks(request):
    
    if request.GET.get('date'):
        
        my_date = datetime.strptime(request.GET.get('date'), "%Y-%M-%d")

        # shows all objects created before this date, but excludes ones sold before
        in_stock = WarehouseItem.objects.filter(created__lte=my_date).exclude(sold__lt=my_date)
        
        import csv
            
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=MRT_STOCKS.csv'

        writer = csv.writer(response)
        for x in in_stock:
            writer.writerow([x.unique_product, x.unique_product.price, x.unique_product.currency])
    
        return response
    
       
    stocks = UniqueProduct.objects.filter(is_active=True, currency__code='GBP')
    
    total_stock_value = 0
    start_date = (datetime.now() - timedelta(weeks=52))
    end_date = datetime.now()
    
    stocks.order_by('parent_product__is_active')
    
    for x in stocks:
        x.uk_stocks = WarehouseItem.objects.filter(
            unique_product=x, 
            sold__isnull=True, 
            location=WarehouseItem.UK
        ).order_by('produced', 'created')
        
        x.china_stocks = WarehouseItem.objects.filter(unique_product=x, sold__isnull=True, location=WarehouseItem.CHINA)
        
        x.in_transit_stocks = WarehouseItem.objects.filter(unique_product=x, sold__isnull=True,
            location=WarehouseItem.IN_TRANSIT)
        
        x.total_value = (x.uk_stocks.count() + x.china_stocks.count() + x.in_transit_stocks.count()) * x.price
        
        x.sold_this_year = WarehouseItem.objects.filter(
            unique_product=x,
            sold__range=(start_date, end_date),
        )
        
        total_stock_value += x.total_value
    
    stocks = sorted(stocks, key=lambda x: x.sold_this_year.count(), reverse=True)
    
    form = AddStocksForm()
    products = UniqueProduct.objects.filter(currency__code='GBP', is_active=True)
    return _render(request, 'my_admin/stocks.html', locals())
Beispiel #11
0
def blog_entry(request, slug):

    entry = get_object_or_404(BlogEntry, slug=slug)
    others = entry.tags.similar_objects()
    
    
    
    try:
        others = others[:2]
    except IndexError:
        pass   
    
    return _render(request, "blog/entry.html", locals())
Beispiel #12
0
def order_complete_fake(request):

    order = Order.objects.filter(date_paid__isnull=False, is_giveaway=False).order_by("?")[0]
    try:
        request.session["ORDER_ID"] = None
    except:
        pass

    try:
        request.session[settings.AFFILIATE_SESSION_KEY] = None  # remove this session key now
    except:
        pass

    return _render(request, "shop/order_complete.html", locals())
Beispiel #13
0
def page(request, slug):

    page = get_object_or_404(Page, slug=slug)

    if page.slug == _("contact-us"):
        form = ContactForm()

    if page.slug == _("learn"):
        pages = Page.objects.filter(parent__parent__slug=_("learn")).order_by("?")[:10]

    template = "shop/page.html"
    if page.template:
        template = page.template
    teas = _get_products(request, random=True)[:2]

    return _render(request, template, locals())
Beispiel #14
0
def index(request):

    curr = RequestContext(request)["currency"]

    teas = Product.objects.filter(
        is_active=True,
        # is_featured=True,
        category__parent_category__slug=_("teas"),
    )[:8]

    for t in teas:
        t.price = t.get_lowest_price(currency=curr)

    blog_entries = BlogEntry.objects.filter(is_promoted=True, is_draft=False).order_by("-date_added")[:2]

    return _render(request, "shop/home.html", locals())
Beispiel #15
0
def order_repeat(request, hash):

    # THE PREVIOUS ORDER ITEM
    old_order = get_object_or_404(Order, hashkey=hash)

    new_order = Order.objects.create(
        date_confirmed=datetime.now(),
        address=old_order.address,
        owner=old_order.owner,
        status=Order.STATUS_CREATED_NOT_PAID,
        invoice_id="TEMP",
    )

    new_order.invoice_id = "TEA-00%s" % (new_order.id)
    new_order.save()

    # we'll also create a basket for them.
    # because IF they want to add something else to the order,
    # they'll need a basket.
    basket = Basket.objects.create(date_modified=datetime.now(), owner=new_order.owner)

    # now we'll check for replacements/substitutions
    currency = _get_currency(request)

    for item in old_order.items.all():
        if item.item.is_active == False:
            # if it's not available, replace it with the closest matching UniqueProduct
            product = UniqueProduct.objects.filter(
                parent_product=item.item.parent_product, sale_price__isnull=True, currency=currency, is_active=True
            ).order_by("-price")[0]
            basket_item = BasketItem.objects.create(item=product, quantity=item.quantity, basket=basket)
            new_order.items.add(basket_item)
        else:
            new_order.items.add(item)

    # for each item attached to the new order, reassign the basket to this new basket
    for item in new_order.items.all():
        item.basket = basket
        item.save()

    request.session["BASKET_ID"] = basket.id
    request.session["ORDER_ID"] = new_order.id

    # FINALLY, GET THE VALUES ETC.
    basket = _get_basket_value(request, order=new_order)

    return _render(request, "shop/forms/order_repeat.html", locals())
Beispiel #16
0
def order_complete(request, hash=None):

    # TRY TO GET THEIR ORDER INFORMATION FROM A COOKIE
    if hash:
        order = get_object_or_404(Order, hashkey=hash)
    else:
        try:
            order = get_object_or_404(Order, id=request.session["ORDER_ID"])
        except:
            pass

    # CLEAR THEIR BASKET (EVERYTHING'S BEEN PAID FOR NOW, RIGHT?)
    from shop.utils import _empty_basket

    _empty_basket(request)

    return _render(request, "shop/order_complete.html", locals())
Beispiel #17
0
def basket(request):

    discount = None
    if request.method == "POST":
        form = UpdateDiscountForm(request.POST)
        if form.is_valid():
            try:
                discount = get_object_or_404(Discount, discount_code=form.cleaned_data["discount_code"], is_active=True)
            except:
                discount = None

            if discount:
                request.session["DISCOUNT_ID"] = discount.id
            else:
                discount_error_message = _("Sorry, that's not a valid discount code!")

    basket = _get_basket_value(request, discount=discount)

    form = UpdateDiscountForm()
    return _render(request, "shop/basket.html", locals())
Beispiel #18
0
def tea_view(request, slug):

    try:
        added = request.session["ADDED"]
    except:
        added = None

    if added:
        try:
            thing = get_object_or_404(BasketItem, id=request.session["ADDED"])
            from shop.templatetags.convert_weights import convert_weights

            weight = convert_weights(request, thing.item.weight)
            message = _("1 x %(weight)s%(unit)s added to your basket!") % {
                "weight": weight,
                "unit": RequestContext(request)["weight_unit"],
            }
            request.session["ADDED"] = None
        except:
            pass

    tea = get_object_or_404(Product, slug=slug)

    try:
        review = Review.objects.filter(is_published=True, product=tea, lang=get_language()).order_by("?")[0]
    except:
        pass

    # IF IT'S A MONTHLY ITEM, LET'S REDIRECT HERE:
    if tea.slug == _("monthly-tea-box"):
        return monthly_tea_box(request)

    recommended = _get_products(request, random=True, exclude=tea.id)[:4]
    prices = UniqueProduct.objects.filter(is_active=True, parent_product=tea, currency=_get_currency(request)).order_by(
        "weight"
    )

    # IN CASE OF DEALS ON THE PAGE
    multiple_form = AddMultipleItemsToBasket()

    return _render(request, "shop/tea_view.html", locals())
Beispiel #19
0
def category(request, slug):
    curr = _get_currency(request)
    if slug == _("teas") or slug == _("teaware"):
        products = None
        category = get_object_or_404(Category, slug=slug)
        categories = Category.objects.filter(parent_category__slug=slug)
        for c in categories:
            c.products = _get_products(request, c.slug)

    else:
        category = get_object_or_404(Category, slug=slug)
        products = _get_products(request, category.slug)

    basket = _get_basket(request)
    if basket and products:
        for x in products:
            basket_item = BasketItem.objects.filter(basket=basket, item=x.get_lowest_price(curr))
            x.price = x.get_lowest_price(curr)
            if basket_item.count() > 0:
                x.basket_quantity = basket_item[0].quantity

    return _render(request, "shop/category.html", locals())
Beispiel #20
0
def monthly_tea_box(request):

    product = get_object_or_404(Product, slug=_("monthly-tea-box"))
    products = Product.objects.filter(category__parent_category__slug=_("teas"), is_active=True)

    basket_items = BasketItem.objects.filter(basket=_get_basket(request))

    try:
        months = int(request.session["MONTHS"])
    except:
        months = settings.TEABOX_DEFAULT_MONTHS

    if product.is_active:
        excluded = []
        total_quantity = 0
        for x in products:

            x.single_price = x.get_lowest_price(_get_currency(request), exclude_sales=True)

            if not x.single_price.stocks():
                excluded.append(x.id)
                continue
                # weird... the above thing doesn't work.

            try:
                x.price = _get_monthly_price(x.single_price, months)
            except:
                x.price = None

            x.quantity = 0
            for y in basket_items:
                if x.single_price == y.item:
                    x.quantity += y.quantity
                    total_quantity += 1

        products.exclude(id__in=excluded, name__icontains=_("taster"))

    return _render(request, "shop/monthly_tea_box.html", locals())
Beispiel #21
0
def review_tea(request, category, slug):
    tea = get_object_or_404(Product, slug=slug)

    if request.method == "POST":
        form = ReviewForm(request.POST)
        if form.is_valid():
            words = form.cleaned_data["text"]
            first_name = form.cleaned_data["first_name"]
            last_name = form.cleaned_data["last_name"]
            email = form.cleaned_data["email"]
            review = Review.objects.create(
                text=words, product=tea, first_name=first_name, last_name=last_name, email=email
            )

            review.save()
            from emailer.views import _admin_notify_new_review

            _admin_notify_new_review(tea, review)

            return HttpResponseRedirect(reverse("review_tea_thanks", args=[tea.category.slug, tea.slug]))

    else:
        form = ReviewForm()
    return _render(request, "shop/forms/review_form.html", locals())
Beispiel #22
0
def staff(request, slug):
    staff = get_object_or_404(Blogger, slug=slug)
    return _render(request, "blog/blogger.html", locals())
Beispiel #23
0
def stats(request):
    if not request.user.is_superuser:
        return HttpResponseRedirect("/")
    
    start_date = (datetime.now() - timedelta(weeks=260))
    w = None
    if request.GET.get('w'):
        w = request.GET.get('w')
        start_date = (datetime.now() - timedelta(weeks=int(w)))    
    end_date = datetime.now()
    
    orders = CustomerPackage.objects.filter(
                order__is_giveaway=False, 
                order__date_paid__range=(start_date, end_date)
                )
    
    tvgbp = 0
    tvusd = 0
    tveur = 0
    total_order_value = 0
    total_items = 0
    av_extra_costs = 0
    pp_cost = 0
    postage_cost = 0
    shoppers = {}
    german_orders_total_value = 0
    italian_orders_total_value = 0
    raph = 0
    german_countries = ('DE', 'AT', 'BE')
    italian_countries = ('IT', 'NL')
    
    for o in orders:
        
        shoppers[o.order.owner] = 1
        
        try:
            code = o.get_final_currency().code
        except AttributeError:
            code = 'GBP'
        
        
        if code == 'GBP':
            currency_converter = 1
            try:
                tvgbp += o.get_final_value()
            except:
                pass
                
        if code == 'USD':
            currency_converter = 0.66
            try:
                tvusd += o.get_final_value() 
            except:
                pass
                
        if code == 'EUR':
            currency_converter = 0.808
            tveur += o.get_final_value()
        
        
        # CALCULATE THE PAYPAL COSTS
        try:
            pp_cost += (float(o.order.get_paypal_ipn().mc_fee) * float(currency_converter))
        except:
            pass
        
        
        try:
            total_items += o.get_items().count()
        except:
            pass
        
        # CALCULATE ABSOLUTE TOTAL AMOUNT IN GBP
        try:       
            total_order_value += float(o.get_final_value()) * float(currency_converter)
        except:
            pass
        
        # CALCULATE THE POSTAGE COSTS
        try:
            postage_cost += float(o.postage_cost) * float(currency_converter)
        except:
            pass    
        
        if o.order.address.country in german_countries:
            amount = float(o.order.get_amount()) * float(currency_converter)
            german_orders_total_value += float(amount)
        
        
        if o.order.address.country in italian_countries:
            amount = float(o.order.get_amount()) * float(currency_converter)
            italian_orders_total_value += float(amount)
            
    
    total_extra_costs = float(pp_cost) + float(postage_cost)
    shoppers = len(shoppers)
    
    # AVERAGES
    av_paypal = pp_cost / orders.count()
    av_postage = postage_cost / orders.count()
    av_order_value = float(total_order_value) / float(orders.count())
    av_order_items = float(total_items) / float(orders.count())
    
    return _render(request, 'my_admin/stats.html', locals())    
Beispiel #24
0
def admin_order(request, id):
    if not request.user.is_superuser:
        return HttpResponseRedirect("/")
    order = get_object_or_404(Order, pk=id)
    return _render(request, 'my_admin/order.html', locals())
Beispiel #25
0
            _payment_success(order)

            # NOW CREATE A CUSTOMER PACKAGE
            from logistics.views import _create_customer_package

            _create_customer_package(order)

            return HttpResponseRedirect(reverse("order_complete", args=[order.hashkey]))
        except stripe.CardError, e:

            # do we need to do something here like show an error message?!

            pass

    return _render(request, "shop/forms/order_confirm.html", locals())


# THIS IS USED AS A CHEAT FOR 100% DISCOUNT ORDERS, FOR TESTING OR WHATEVER
def fake_checkout(request, order_id):

    order = get_object_or_404(Order, pk=order_id)

    # DOUBLE CHECK THE ORDER HAS 100% DISCOUNT
    # if not order.discount or order.discount.discount_value < 1:
    #    return HttpResponseRedirect(reverse('order_confirm'))

    # ORGANISE THE ORDER AS IF IT HAD BEEN PAID LIKE NORMAL
    order.status = Order.STATUS_PAID
    order.date_paid = datetime.now()
    order.notes = "100% discount order, not paid via paypal."
Beispiel #26
0
def review_tea_thanks(request, category, slug):
    message = _(
        "Thanks for posting your review! It's really important to us and we will read and respond to any suggetions you've made."
    )
    return _render(request, "shop/message.html", locals())
Beispiel #27
0
def reviews(request):
    reviews = Review.objects.filter(is_published=True).order_by("-date_submitted")
    return _render(request, "shop/reviews.html", locals())
Beispiel #28
0
def order_url(request, hash, friend=None):
    order = get_object_or_404(Order, hashkey=hash)
    basket = _get_basket_value(request, order=order)
    return _render(request, "shop/forms/order_confirm.html", locals())
Beispiel #29
0
def order_step_one(request, basket=None):

    try:
        basket = Basket.objects.get(id=request.session["BASKET_ID"])
    except:
        pass

    try:
        order = get_object_or_404(Order, id=request.session["ORDER_ID"])
        email = order.owner.email
        house_name_number = order.address.house_name_number
        address_line_1 = order.address.address_line_1
        address_line_2 = order.address.address_line_2
        town_city = order.address.town_city
        postcode = order.address.postcode
        province_state = order.address.province_state
        country = order.address.country
        first_name = order.owner.first_name
        last_name = order.owner.last_name
    except:
        order = None

    if not basket and not order:
        problem = _("You don't have any items in your basket, so you can't process an order!")
        return _render(request, "shop/order-problem.html", locals())

    if request.method == "POST":
        post_values = request.POST.copy()
        initial_values = (
            _("First name"),
            _("Last name"),
            _("Email address"),
            _("Your address..."),
            _(" ...address continued (optional)"),
            _("Town or city"),
            _("State"),
            _("Post / ZIP code"),
            _("invalid"),
        )

        for k, v in post_values.iteritems():
            if v in initial_values:
                del post_values[k]

        form = OrderStepOneForm(post_values)
        if form.is_valid():

            # FIRST, GET THE USER
            if request.user.is_authenticated():
                user = request.user
            else:

                try:
                    user = User.objects.filter(email=form.cleaned_data["email"])[0]

                except IndexError:
                    creation_args = {
                        "username": form.cleaned_data["email"],
                        "email": form.cleaned_data["email"],
                        "password": uuid.uuid1().hex,
                    }
                    user = User.objects.create(**creation_args)
                    user.first_name = form.cleaned_data["first_name"]
                    user.last_name = form.cleaned_data["last_name"]
                    user.save()

            try:
                shopper = get_object_or_404(Shopper, user=user)
            except MultipleObjectsReturned:
                shopper = Shopper.objects.filter(user=user)[0]

            except:
                creation_args = {
                    "user": user,
                    "email": user.email,
                    "first_name": user.first_name,
                    "last_name": user.last_name,
                    "slug": smart_slugify(
                        "".join((form.cleaned_data["first_name"], form.cleaned_data["last_name"])), lower_case=True
                    ),
                    "language": get_language(),
                }
                shopper = Shopper.objects.create(**creation_args)

            # CREATE AN ADDRESS OBJECT
            address = Address.objects.create(
                owner=shopper,
                house_name_number=form.cleaned_data["house_name_number"],
                address_line_1=form.cleaned_data["address_line_1"],
                address_line_2=form.cleaned_data["address_line_2"],
                town_city=form.cleaned_data["town_city"],
                postcode=form.cleaned_data["postcode"],
                country=form.cleaned_data["country"],
            )

            try:
                address.province_state = form.cleaned_data["province_state"]
                address.save()
            except:
                pass

            # if they agree to get an email newsletter
            if form.cleaned_data["newsletter"] == True:
                from signals import update_mailing_list

                update_mailing_list.send(
                    sender=update_mailing_list, email_address=form.cleaned_data["email"], lang_code=get_language()
                )

            # CREATE OR FIND THE ORDER
            try:
                order = get_object_or_404(Order, id=request.session["ORDER_ID"])
                if not order.hashkey:
                    order.hashkey = uuid.uuid1().hex
                    order.save()

            except:
                creation_args = {
                    "date_confirmed": datetime.now(),
                    "address": address,
                    "owner": shopper,
                    "status": Order.STATUS_CREATED_NOT_PAID,
                    "invoice_id": "TEMP",
                    "hashkey": uuid.uuid1().hex,
                }
                order = Order.objects.create(**creation_args)
                order.save()  # need to save it first, then give it an ID
                if settings.AFFILIATE_SESSION_KEY in request.session:
                    order.invoice_id = "TEA-00%sA" % (order.id)
                    order.affiliate_referrer = request.session[settings.AFFILIATE_SESSION_KEY]
                else:
                    order.invoice_id = "TEA-00%s" % (order.id)

            # DO THEY HAVE A VALID DISCOUNT CODE?
            try:
                discount = get_object_or_404(Discount, pk=request.session["DISCOUNT_ID"])
                order.discount = discount
            except:
                pass

            # UPDATE ORDER WITH THE BASKET ITEMS
            basket_items = BasketItem.objects.filter(basket=basket)
            for item in basket_items:
                order.items.add(item)

            order.save()
            request.session["ORDER_ID"] = order.id

            # FINALLY! WE'RE DONE
            return HttpResponseRedirect(reverse("order_confirm"))

        # IF THE FORM HAS ERRORS:
        else:

            # LOAD EXISTING DATA
            email = request.POST["email"]
            house_name_number = request.POST["house_name_number"]
            address_line_1 = request.POST["address_line_1"]
            address_line_2 = request.POST["address_line_2"]
            town_city = request.POST["town_city"]
            postcode = request.POST["postcode"]
            country = request.POST["country"]
            first_name = request.POST["first_name"]
            last_name = request.POST["last_name"]

            try:
                province_state = request.POST["province_state"]
            except:
                pass

            form = OrderStepOneForm(post_values)

    else:
        form = OrderStepOneForm()
    return _render(request, "shop/forms/order_step_one.html", locals())