Skip to content

Instantly share code, notes, and snippets.

@zbyte64
Created February 2, 2013 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zbyte64/4699507 to your computer and use it in GitHub Desktop.
Save zbyte64/4699507 to your computer and use it in GitHub Desktop.
Example of using Django forms to load CSVs
from simplecart.discounts.models import *
from simplecart.orders.models import SKU
from decimal import Decimal
import datetime
from django import forms
class r(str):
pass
DISCOUNT_CHOICES = [
'absolute',
'percent',
#'free_ship',
]
class CouponForm(forms.Form):
coupon = forms.CharField()
discount = forms.DecimalField()
coupon_type = forms.ChoiceField(choices=zip(DISCOUNT_CHOICES, DISCOUNT_CHOICES))
productid = forms.IntegerField(required=False)
categoryid = forms.IntegerField(required=False)
minimum = forms.IntegerField()
times = forms.IntegerField()
times_used = forms.IntegerField()
expire = forms.CharField()
def clean_expire(self):
expire = self.cleaned_data.get('expire')
#Friday 06 May 2011 12:00:00 AM
try:
return datetime.datetime.strptime(expire, '%A %d %B %Y %I:%M:%S %p')
except ValueError, e:
raise forms.ValidationError(str(e))
def get_coupon(self):
try:
coupon = Coupon.objects.get(code=self.cleaned_data['coupon'])
coupon.discounts.all().delete()
except Coupon.DoesNotExist:
coupon = Coupon(code=self.cleaned_data['coupon'], rules={})
if self.cleaned_data['times']:
coupon.max_uses = self.cleaned_data['times'] - self.cleaned_data['times_used']
else:
coupon.max_uses = None
if self.cleaned_data['minimum']:
coupon.min_amount = self.cleaned_data['minimum']
else:
coupon.min_amount = None
coupon.name = coupon.code
coupon.expiration_date = self.cleaned_data['expire']
coupon.save()
return coupon
def get_discount_type(self):
if self.cleaned_data['coupon_type'] == 'absolute':
return 'A'
if self.cleaned_data['coupon_type'] == 'percent':
return 'P'
def do_product_discount(self):
coupon = self.get_coupon()
ProductDiscount(rules={"prototype": "if",
"evaluation": "TRUE",
"concatenation": "ALL",
"conditions": [{"prototype": "product",
"product":self.cleaned_data['productid'],}]},
coupon=coupon,
short_description='Product Discount',
discount=self.cleaned_data['discount'],
discount_type=self.get_disocunt_type(),).save()
return coupon
def do_category_discount(self):
coupon = self.get_coupon()
ProductDiscount(rules={"prototype": "if",
"evaluation": "TRUE",
"concatenation": "ALL",
"conditions": [{"prototype": "productcategory",
"category":self.cleaned_data['categoryid'],}]},
coupon=coupon,
short_description='Product Discount',
discount=self.cleaned_data['discount'],
discount_type=self.get_discount_type(),).save()
return coupon
def do_order_discount(self):
coupon = self.get_coupon()
discount = OrderDiscount(coupon=coupon,
rules={},
short_description='Order Discount',
discount=self.cleaned_data['discount'],
discount_type=self.get_discount_type(),
stop_other_discounts=True)
discount.save()
return coupon
def save(self):
if self.cleaned_data['productid']:
return self.do_product_discount()
if self.cleaned_data['categoryid']:
return self.do_category_discount()
return self.do_order_discount()
from django.core.management.base import BaseCommand
from django.utils.datastructures import MultiValueDict
import csv
class Command(BaseCommand):
help = "Imports a csv file describing a set of coupons"
args = "<coupon.csv>"
def make_dictionary(self, header, row):
data = MultiValueDict()
for key, value in zip(header, row):
data.appendlist(key, value.strip())
return data
def prep_header(self, header):
ret = list()
for row in header:
ret.append(row.lower().strip('!').strip())
return ret
def handle(self, filename, *args, **options):
from couponimporter.forms import CouponForm
rows = csv.reader(open(filename, 'r'))
rows.next() #first row is junk
header = self.prep_header(rows.next())
form_cls = CouponForm
for index, row in enumerate(rows):
form = form_cls(data=self.make_dictionary(header, row))
if form.is_valid():
form.save()
else:
row_num = index + 2
print 'Row %s is not valid.' % row_num
print 'Row %s contained: %s' % (row_num, form.data)
print 'It had the following errors:'
print form.errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment