PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/business/views.py

https://github.com/john2x/pley
Python | 334 lines | 322 code | 7 blank | 5 comment | 5 complexity | 3175a3da404af8655ae6079121dcd227 MD5 | raw file
Possible License(s): JSON
  1. # Create your views here.
  2. from django.http import HttpResponse, Http404
  3. from django.template import Context, loader, RequestContext
  4. from django.shortcuts import render_to_response, redirect
  5. from django.db import transaction, IntegrityError
  6. from django.contrib.auth.decorators import login_required
  7. from django.core.paginator import Paginator, InvalidPage, EmptyPage
  8. from django.core import serializers
  9. from django.forms.formsets import formset_factory
  10. from django.core.exceptions import ObjectDoesNotExist
  11. from pley.business.models import *
  12. from pley.review.models import *
  13. from pley.business.forms import *
  14. import simplejson as json
  15. import urllib
  16. from geopy import geocoders
  17. from django.conf import settings
  18. def business_home(request):
  19. data = {}
  20. return render_to_response("business/business_home.html",
  21. data, context_instance=RequestContext(request))
  22. def business_view_v3_localsearch(request, business_id):
  23. business_item = Business.objects.select_related().get(id=business_id)
  24. phone_list = Phone.objects.filter(business=business_id)
  25. reviews = Review.objects.filter(business=business_id)
  26. detail_list = BusinessDetails.objects.filter(business=business_id)
  27. time_list = BusinessHours.objects.filter(business=business_id)
  28. category_list = BusinessCategory.objects.filter(business=business_id)
  29. payment_options = BusinessPaymentOptions.objects.filter(business=business_id)
  30. print 'Payment: ', payment_options
  31. tags = business_item.tags.all()
  32. # Check if user already reviewed this business
  33. try:
  34. if request.user.is_authenticated():
  35. user_review = Review.objects.get(business=business_item, user=request.user, status='A')
  36. else:
  37. raise ObjectDoesNotExist
  38. except ObjectDoesNotExist:
  39. user_review = None
  40. print user_review
  41. ###############
  42. # Google Maps #
  43. ###############
  44. google_apikey = settings.GOOGLE_MAPS_KEY
  45. string_location = business_item.address1 + ', ' +business_item.address2 + ', ' + business_item.city + ', ' + business_item.province + ', ' + business_item.country + ', ' + business_item.zipcode
  46. clean_string_location = ''.join([letter for letter in string_location if not letter.isdigit()])
  47. urlencoded_string_location = urllib.quote_plus(string_location)
  48. business_form = BusinessForm()
  49. business_category_form = BusinessCategoryForm()
  50. phone_form = PhoneForm()
  51. latlng_form = BusinessFormSaveLatLng()
  52. ###############
  53. data = {"business_item": business_item,
  54. "phone_list": phone_list,
  55. "detail_list": detail_list,
  56. "time_list": time_list,
  57. "category_list": category_list,
  58. "payment_options": payment_options,
  59. "reviews":reviews,
  60. "string_location":string_location,
  61. "clean_string_location":clean_string_location,
  62. "view_name": request.path,
  63. "urlencoded_string_location":urlencoded_string_location,
  64. "google_apikey":google_apikey,
  65. "business_form": business_form,
  66. "business_category_form": business_category_form,
  67. "latlng_form": latlng_form,
  68. "phone_form": phone_form,
  69. "user_review": user_review,
  70. "tags": tags,
  71. }
  72. return render_to_response("business/business_view_v3_localsearch.html",
  73. data, context_instance=RequestContext(request))
  74. def business_browse(request):
  75. #my_objects = get_list_or_404(MyModel, published=True)
  76. business_list = Business.objects.filter(status='A').order_by('-created_at')
  77. paginator = Paginator(business_list, settings.PAGE_ITEMS)
  78. try:
  79. page = int(request.GET.get('page','1'))
  80. except ValueError:
  81. page = 1
  82. try:
  83. businesses = paginator.page(page)
  84. except (EmptyPage, InvalidPage):
  85. businesses = paginator.page(paginator.num_page)
  86. # get categories
  87. category_list = []
  88. for business in businesses.object_list:
  89. business_category_list = BusinessCategory.objects.filter(business=business)
  90. categories = []
  91. for business_category in business_category_list:
  92. categories.append(business_category.category.name)
  93. category_list.append(categories)
  94. business_and_categories_list = zip(businesses.object_list, category_list)
  95. data = {
  96. "business_list": business_list,
  97. "businesses": businesses,
  98. "category_list": category_list,
  99. "business_and_categories_list": business_and_categories_list,
  100. }
  101. return render_to_response("business/business_browse.html",
  102. data, context_instance=RequestContext(request))
  103. @login_required
  104. @transaction.commit_manually
  105. def save_latlng(request, business_id):
  106. success = False
  107. error = None
  108. if request.method == 'POST' and request.is_ajax():
  109. latlng_form = BusinessFormSaveLatLng(request.POST)
  110. if(latlng_form.is_valid()):
  111. try:
  112. lat = latlng_form.cleaned_data['lat']
  113. lng = latlng_form.cleaned_data['lng']
  114. business = Business.objects.get(id=business_id)
  115. business.lat = lat
  116. business.lng = lng
  117. business.save()
  118. except IntegrityError, e:
  119. transaction.rollback()
  120. success = False
  121. error = e
  122. data = json.dumps({"status":"failed", "error": error})
  123. return HttpResponse(data)
  124. else:
  125. transaction.commit()
  126. success = True
  127. else:
  128. data = json.dumps({"status":"failed", "error": "Not POST / AJAX."})
  129. return HttpResponse(data)
  130. data = json.dumps({"status":"success"})
  131. return HttpResponse(data)
  132. @login_required
  133. @transaction.commit_manually
  134. def business_add(request):
  135. success = False
  136. error = None
  137. category_count = 1
  138. detail_count = 1
  139. CategoriesFormSet = formset_factory(BusinessCategoryForm, extra=category_count, max_num=5)
  140. HoursFormSet = formset_factory(BusinessHoursForm, extra=7, max_num=7)
  141. DetailsFormSet = formset_factory(BusinessDetailsForm, extra=detail_count)
  142. if request.method == 'POST':
  143. business_form = BusinessForm(request.POST)
  144. hidden_form = HiddenForm(request.POST)
  145. phone_form = PhoneForm(request.POST)
  146. business_payment_options_form = BusinessPaymentOptionsForm(request.POST)
  147. if hidden_form.is_valid():
  148. category_count = hidden_form.cleaned_data['category_count']
  149. detail_count = hidden_form.cleaned_data['detail_count']
  150. if category_count > 5:
  151. category_count = 5
  152. else:
  153. category_count = 1
  154. detail_count = 1
  155. # Business Categories Formset
  156. categories_formset_additional_data = {
  157. 'form-TOTAL_FORMS': u'%d' % category_count,
  158. 'form-INITIAL_FORMS': u'%d' % category_count,
  159. 'form-MAX_NUM_FORMS': u'5',
  160. }
  161. categories_formset = CategoriesFormSet(dict(request.POST.items() + categories_formset_additional_data.items()))
  162. # Business Hours Formset
  163. hours_formset_additional_data = {
  164. 'form-TOTAL_FORMS': u'7',
  165. 'form-INITIAL_FORMS': u'7',
  166. 'form-MAX_NUM_FORMS': u'7',
  167. }
  168. hours_formset = HoursFormSet(dict(request.POST.items() + hours_formset_additional_data.items()))
  169. # Business Details Formset
  170. details_formset_additional_data = {
  171. 'form-TOTAL_FORMS': u'%d' % detail_count,
  172. 'form-INITIAL_FORMS': u'%d' % detail_count,
  173. 'form-MAX_NUM_FORMS': u'',
  174. }
  175. details_formset = DetailsFormSet(dict(request.POST.items() + details_formset_additional_data.items()))
  176. if (business_form.is_valid() and categories_formset.is_valid() and
  177. phone_form.is_valid() and business_payment_options_form.is_valid() and
  178. hours_formset.is_valid() and details_formset.is_valid()):
  179. tags = business_form.cleaned_data['tags']
  180. business_name = business_form.cleaned_data['name']
  181. website = business_form.cleaned_data['website']
  182. address_1 = business_form.cleaned_data['address1']
  183. address_2 = business_form.cleaned_data['address2']
  184. address_city = business_form.cleaned_data['city']
  185. address_province = business_form.cleaned_data['province']
  186. address_country = business_form.cleaned_data['country']
  187. # TODO: zipcode should be found in zipcode table
  188. address_zipcode = business_form.cleaned_data['zipcode']
  189. description = business_form.cleaned_data['description']
  190. phone = phone_form.cleaned_data['phone']
  191. alt = phone_form.cleaned_data['alternate']
  192. fax = phone_form.cleaned_data['fax']
  193. mobile = phone_form.cleaned_data['mobile']
  194. payment_cash = business_payment_options_form.cleaned_data['cash']
  195. payment_credit_card = business_payment_options_form.cleaned_data['credit_card']
  196. payment_debit_card = business_payment_options_form.cleaned_data['debit_card']
  197. payment_cheque = business_payment_options_form.cleaned_data['cheque']
  198. payment_gift_cert = business_payment_options_form.cleaned_data['gift_cert']
  199. payment_others = business_payment_options_form.cleaned_data['others']
  200. # TODO: catch possible exceptions here
  201. try:
  202. print 'saving'
  203. business = Business(name=business_name,address1=address_1, address2=address_2,
  204. city=address_city, province=address_province,
  205. country=address_country, created_by=request.user,
  206. zipcode=address_zipcode, description=description,
  207. website=website)
  208. business.save()
  209. print 'businss saved'
  210. phone = Phone(business=business, phone=phone, alternate=alt, fax=fax, mobile=mobile)
  211. print 'phone created'
  212. phone.save()
  213. print 'business and phone saved'
  214. payment_options = BusinessPaymentOptions(business=business,
  215. cash=payment_cash,
  216. credit_card=payment_credit_card,
  217. debit_card=payment_debit_card,
  218. cheque=payment_cheque,
  219. gift_cert=payment_gift_cert,
  220. others=payment_others)
  221. print 'payment saved'
  222. for category_form in categories_formset.forms:
  223. category = category_form.cleaned_data['category']
  224. business_category = BusinessCategory(business=business,category=category)
  225. business_category.save()
  226. print 'categories done'
  227. for hours_form in hours_formset.forms:
  228. day = hours_form.cleaned_data['day']
  229. open1 = hours_form.cleaned_data['time_open_1']
  230. open2 = hours_form.cleaned_data['time_open_2']
  231. close1 = hours_form.cleaned_data['time_close_1']
  232. close2 = hours_form.cleaned_data['time_close_2']
  233. closed = hours_form.cleaned_data['closed']
  234. business_hours = BusinessHours(business=business,day=day,time_open_1=open1,time_open_2=open2,
  235. time_close_1=close1,time_close_2=close2,closed=closed)
  236. business_hours.save()
  237. print 'hours done'
  238. for tag in tags:
  239. business.tags.add(tag)
  240. for detail_form in details_formset.forms:
  241. field_name = detail_form.cleaned_data['field_name']
  242. field_value = detail_form.cleaned_data['field_value']
  243. business_detail = BusinessDetails(business=business,
  244. field_name=field_name,
  245. field_value=field_value)
  246. business_detail.save()
  247. print 'details done'
  248. except IntegrityError, e:
  249. transaction.rollback()
  250. success = False
  251. error = e
  252. raise e
  253. else:
  254. transaction.commit()
  255. success = True
  256. else:
  257. hidden_form = HiddenForm()
  258. business_form = BusinessForm()
  259. categories_formset = CategoriesFormSet()
  260. phone_form = PhoneForm()
  261. business_payment_options_form = BusinessPaymentOptionsForm()
  262. hidden_form = HiddenForm()
  263. details_formset = DetailsFormSet()
  264. initial_days = [
  265. {'day':u'mon'},
  266. {'day':u'tue'},
  267. {'day':u'wed'},
  268. {'day':u'thu'},
  269. {'day':u'fri'},
  270. {'day':u'sat'},
  271. {'day':u'sun'},
  272. ]
  273. hours_formset = HoursFormSet(initial=initial_days)
  274. data = {
  275. "business_form": business_form,
  276. "phone_form": phone_form,
  277. "business_payment_options_form": business_payment_options_form,
  278. "hidden_form": hidden_form,
  279. "categories_formset": categories_formset,
  280. "hours_formset": hours_formset,
  281. "details_formset": details_formset,
  282. "success": success,
  283. "error": error
  284. }
  285. '''
  286. Check if save thru AJAX or normal POST
  287. '''
  288. if(success):
  289. if request.is_ajax():
  290. results = {"status":"success", "message":"Business saved."}
  291. data = json.dumps(results)
  292. return HttpResponse(data)
  293. else:
  294. return render_to_response("business/business_add.html",
  295. data, context_instance=RequestContext(request))
  296. else:
  297. if request.is_ajax():
  298. data = json.dumps({"status":"failed", "error":error, "data":request.POST})
  299. return HttpResponse(data)
  300. else:
  301. return render_to_response("business/business_add.html",
  302. data, context_instance=RequestContext(request))