public
Created

Example of using Django forms to load CSVs

  • Download Gist
forms.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
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()
import_coupons.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.