def node(self, request): # get cms from cubane.cms.views import get_cms cms = get_cms() # root level (pages and directory categories) if 'pk' not in request.GET and 'type' not in request.GET: return to_json_response({ 'success': True, 'items': [cms.get_sitemap_item(request, page) for page in cms.get_sitemap_root_pages()] }) # get pk argument if 'pk' not in request.GET: raise Http404('Missing argument: pk.') try: pk = int(request.GET.get('pk')) except ValueError: raise Http404('Invalid pk argument: Not a number.') # get type argument if 'type' not in request.GET: raise Http404('Missing argument: type.') type_name = request.GET.get('type') # resolve type by given name model = None for m in get_models(): if m.__name__ == type_name: model = m break if not model: raise Http404('Unknown model type name: \'%s\'.' % type_name) # get node by given pk node = model.objects.get(pk=pk) # generate child nodes items = [] children = cms.get_sitemap_children(node) if children: for child in children: item = cms.get_sitemap_item(request, child) if item: items.append(item) # return response (json) return to_json_response({ 'success': True, 'items': items })
def postcode_lookup(request): postcode = request.GET.get('postcode', None) postcode_provider = _postcode_provider_by_identifier( settings.POSTCODE_PROVIDER) return to_json_response(postcode_provider.get_addresses(postcode))
def product_price(request): """ Calculate the total product price for the given product and the given varieties. """ # arguments product_id = request.GET.get('product', None) if not product_id: raise Http404('Argument product required.') try: ids = [int(x) for x in request.GET.getlist('varieties[]')] except ValueError: raise Http404('Invalid numeric argument for varieties.') try: quantity = int(request.GET.get('quantity', 1)) except ValueError: raise Http404('Invalid numeric value for quantity argument.') # get product product = get_object_or_404(get_product_model(), pk=product_id, client=request.client) # get variety options varieties = list(VarietyAssignment.objects.select_related('variety_option').filter( id__in=ids, product=product )) return to_json_response({ 'net': quantity * (product.net_price + sum([option.price_net for option in varieties])), 'gross': quantity * (product.gross_price + sum([option.price_gross for option in varieties])) })
def update_seq(self, request, variety_id=None): variety = get_object_or_404(Variety, pk=variety_id) option_ids = [parse_int(x, 0) for x in request.POST.getlist('option[]')] if any(map(lambda x: x == 0, option_ids)): raise Http404('Unable to parse option id list.') options = list(variety.options.order_by('seq', 'id')) for i, oid in enumerate(option_ids, start = 1): o = [o for o in options if o.id == oid][0] o.seq = i o.save() return to_json_response({'success': True})
def varieties_delete(self, request, product_id, variety_id): product = get_object_or_404(get_product_model(), pk=product_id) variety = get_object_or_404(Variety, pk=variety_id) assignments = VarietyAssignment.objects.filter( product=product, variety_option__variety=variety) # delete assignments for assignment in assignments: request.changelog.delete(assignment) assignment.delete() request.changelog.commit( 'Variety <em>%s</em> removed.' % variety.title, product) return to_json_response({ 'success': True, })
def delete(self, request, pk=None): """ Delete existing model instance with given primary key pk or (if no primary key is given in the url) attempt to delete multiple entities that are given by ids post argument. """ # determine list of pks pks = [] if pk: pks = [pk] else: pks = request.POST.getlist('pks[]', []) if len(pks) == 0: pk = request.POST.get('pk') if pk: pks = [pk] # delete instance(s)... if len(pks) == 1: instance = self.get_object_or_404(request, pks[0]) label = instance.__unicode__() if not label: label = '<no label>' instance.delete() message = self._get_success_message(label, 'deleted') else: instances = self._get_objects(request).filter(pk__in=pks) for instance in instances: instance.delete() message = '%d %s deleted successfully.' % ( len(instances), self.model._meta.verbose_name_plural) # response if self._is_json(request): return to_json_response({'success': True, 'message': message}) else: messages.add_message(request, messages.SUCCESS, message) return self._redirect(request, 'index')
def default_enquiry_form(request, context, template_context, modelclass, formclass=None): """ Default View handler for processing the given enquiry form. If no form is given, the default form is determined by the get_form class method of the given enquiry model. """ if 'cubane.cms' not in settings.INSTALLED_APPS: raise ValueError('cubane.cms required for sending cms page emails.') if not hasattr(settings, 'ENQUIRY_CLIENT_TEMPLATE'): raise ValueError( "'ENQUIRY_CLIENT_TEMPLATE' is required in settings for sending " + \ "emails to clients." ) if not formclass: formclass = modelclass.get_form() if formclass: from cubane.cms.views import get_cms cms = get_cms() if request.method == 'POST': form = formclass(request.POST) else: initial = {} for k, v in request.GET.items(): initial[k] = v form = formclass(initial=initial) remove_backend_fields(form) if getattr(form, 'configure'): cms.enquiry_configure_form(request, form, instance=None, edit=False) if request.method == 'POST': captcha = validate_captcha(request) if not captcha: messages.add_message( request, messages.ERROR, 'Please tick the checkbox at the bottom of the form to prevent SPAM.' ) if form.is_valid() and captcha: # don't save the request on the backend if no enquiry_email is present # just present an error message, that the functionality isn't working atm if not cms.settings.enquiry_email: msg = 'Our enquiry form isn\'t working at the moment ' +\ 'because we don\'t have an email address yet. ' +\ 'Please use other means of contacting us.' if request.is_ajax(): return to_json_response({ 'errors': { '__all__': [msg] }, 'success': False }) else: messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect( no_cache_url(request.get_full_path())) d = form.cleaned_data instance = modelclass() save_model(d, instance) # success message (unless this is an ajax call) if not request.is_ajax(): messages.add_message( request, messages.SUCCESS, 'Thank you for your enquiry. We will contact you shortly.' ) # send email to website visitor cms.enquiry_send_mail_to_customer(request, instance, d) # remove captcha information from the email to the client if 'captcha' in d: del d['captcha'] if 'captcha_hash' in d: del d['captcha_hash'] # send email to client cms.enquiry_send_mail_to_client(request, instance, d) # successfull enquiry made cms.on_enquiry_send(request, instance, d) # send response if request.is_ajax(): return to_json_response({'success': True}) else: return HttpResponseRedirect( no_cache_url(request.get_full_path())) else: # if form is not valid or captcha failed if request.is_ajax(): errors = form._errors if not captcha: if '__all__' not in errors: errors['__all__'] = [] errors['__all__'].append( 'Please tick the checkbox at the bottom of the form to prevent SPAM.' ) return to_json_response({ 'success': False, 'errors': errors }) template_context.update({'enquiry_form': form}) return template_context
def test_should_support_deprecated_argument_mimetype(self): r = to_json_response({'foo': 'bar'}, content_type='a', mimetype='b') self.assertEqual('b', r['Content-Type'])
def test_should_return_json_response_with_content_type_javascript(self): r = to_json_response({'foo': 'bar'}) self.assertEqual(200, r.status_code) self.assertEqual('text/javascript', r['Content-Type']) self.assertEqual('{"foo":"bar"}', r.content)
def update(request): """ Update basket. This may also trigger "continue shopping" and "checkout". """ # get prefix prefix = get_basket_prefix(request, request.POST) # get basket basket = Basket(request, prefix=prefix) return_url = get_return_url(request) # keep track of removed items removed_items = [] def add_removed_item(item): removed_items.append(item) if not basket.is_frozen: # update quantity for item in list(basket.items): k = 'qty_%s' % item.hash if k in request.POST: try: qty = int(request.POST.get(k, 0)) except ValueError: qty = 0 removed = basket.update_quantity_by_hash(item.hash, qty) if removed: add_removed_item(item) # remove item item_hash = request.POST.get('remove_basket_item', '') if item_hash != '': item = basket.remove_item_by_hash(item_hash) if item: add_removed_item(item) # voucher if 'voucher-code' in request.POST: voucher_code = request.POST.get('voucher-code') if voucher_code: voucher_code = voucher_code.upper() if voucher_code: if voucher_code != basket.get_voucher_code(): # add voucher code to basket if not basket.set_voucher(voucher_code): if not request.is_ajax(): messages.error( request, 'Expired or unrecognised voucher code.') else: basket.remove_voucher() # delivery country if 'country_iso' in request.POST: try: country = Country.objects.get( iso=request.POST.get('country_iso')) basket.set_delivery_country(country) except Country.DoesNotExist: pass # custom total (staff only) if request.user.is_staff or request.user.is_superuser: if 'custom-total' in request.POST: custom_total = request.POST.get('custom-total') if custom_total == '': basket.clear_custom_total() else: custom_total = Decimal(custom_total) basket.set_custom_total(custom_total) # click and collect if 'click_and_collect' in request.POST: basket.set_click_and_collect( request.POST.get('click_and_collect') in ['true', 'on']) # delivery option option_id = request.POST.get('delivery_option_id', None) delivery_option_details = None if option_id: try: option = DeliveryOption.objects.get(pk=option_id, enabled=True) delivery_option_details = basket.get_delivery_details(option) basket.set_delivery_option(option) except DeliveryOption.DoesNotExist: pass # processing state (backend only) if request.user.is_staff or request.user.is_superuser: for item in list(basket.items): k = 'processed_%s' % item.hash if k in request.POST: processed = request.POST.get(k, 'off') == 'on' basket.update_processed_by_hash(item.hash, processed) # save changes to basket basket.save() # ajax? if request.is_ajax(): basket = Basket(request, prefix=prefix) return to_json_response({ 'success': True, 'prefix': basket.prefix, 'html': get_basket_html(request, basket), 'delivery': get_delivery_option_details_html(request, delivery_option_details), 'is_collection_only': basket.is_collection_only(), 'finance_options': [option.to_dict() for option in basket.get_finance_options()], 'removed': [item.to_ga_dict() for item in removed_items] }) # next action = request.POST.get('action', 'update') if action == 'continue': return HttpResponseRedirect(return_url) elif action == 'checkout': return HttpResponseRedirect(reverse('shop.order.delivery')) else: return HttpResponseRedirect(return_url)
def add(request): """ Add given product to the customer's basket and redirect to the basket page. """ product = get_product_or_404(request) return_url = get_return_url(request) form = AddToBasketForm(request.POST, request=request, product=product) variant = '' quantity = 0 price = 0 prefix = None if form.is_valid(): d = form.cleaned_data variety_options = form.get_variety_options() variety_option_labels = form.get_variety_option_labels(variety_options) variant = ', '.join([option.title for option in variety_options]) quantity = form.get_quantity() prefix = get_basket_prefix(request, d) # add to basket basket = Basket(request, prefix=prefix) item = basket.add_item(product, variety_options, quantity, custom=None, labels=variety_option_labels) if item: price = item.total_product else: messages.error( request, "Please note that the product '%s' cannot be added to basket." % product.title) # alert for non-returnable products if product.non_returnable: messages.warning( request, "Please note that the product '%s' cannot be returned." % product.title) # hook shop = get_shop() shop.on_basket_added(request, basket, product, variety_options, quantity) basket.save() errors = False else: errors = form.errors if request.is_ajax(): basket = Basket(request, prefix=prefix) return to_json_response({ 'success': True, 'html': get_basket_html(request, basket), 'errors': errors, 'prefix': basket.prefix, 'added': product.to_ga_dict({ 'variant': variant, 'quantity': quantity, 'price': price }) }) else: return HttpResponseRedirect(return_url)
def _create_edit(self, request, pk=None, edit=False, duplicate=False): if not edit and len(request.FILES.getlist('media')) > 1: # cancel? if request.POST.get('cubane_form_cancel', '0') == '1': return self._redirect(request, 'index') kwargs = {} # create form if request.method == 'POST': form = MultiMediaForm(request.POST, request.FILES, **kwargs) else: form = MultiMediaForm(**kwargs) form.configure(request) # validate form if request.method == 'POST' and form.is_valid(): # update properties in model instance d = form.cleaned_data if 'media' in request.FILES: file_list = request.FILES.getlist('media') n = 0 Progress.start(request, len(file_list)) first_instance = None for f in file_list: instance = self.model() instance.parent = d.get('parent') if first_instance is None: first_instance = instance # auto fit if settings.IMAGE_FITTING_ENABLED and settings.IMAGE_FITTING_SHAPES: instance.auto_fit = d.get('auto_fit') # jpeg quality instance.jpeg_quality = d.get('jpeg_quality') # save instance.save() instance.upload_save_from_stream(f, request=request) n += 1 request.changelog.create(instance) # notify task runner to do the job if instance.is_blank: TaskRunner.notify() # report progress made Progress.set_progress(request, n) # commit changes message = '<em>%d</em> %s created.' % ( n, self.model._meta.verbose_name_plural) change = request.changelog.commit(message, model=self.model) Progress.stop(request) # ajax operation, simply return success and message # information if request.is_ajax(): return to_json_response({ 'success': True, 'message': message, 'change': change, 'next': self._get_url(request, 'index', namespace=True), 'instance_id': first_instance.pk, 'instance_title': unicode(first_instance), }) # dialog or screen? if request.GET.get('create', 'false') == 'true': return { 'dialog_created_id': instance.pk, 'dialog_created_title': unicode(instance) } else: return self._redirect(request, 'index') elif request.is_ajax(): return to_json_response({ 'success': False, 'errors': form.errors }) context = { 'form': form, 'permissions': { 'create': self.user_has_permission(request.user, 'add'), 'view': self.user_has_permission(request.user, 'view'), 'edit': self.user_has_permission(request.user, 'edit') }, 'verbose_name': 'Multiple Media' } else: if request.method == 'POST': Progress.start(request, 1) context = super(MediaView, self)._create_edit(request, pk, edit, duplicate) if isinstance(context, dict): context['is_images'] = isinstance(self, ImageView) return context