def get_detail(self):
     """Returns extra detail as defined by get_order_detail()"""
     if not hasattr(self, '_detail_cache'):
         model_cls = helpers.get_order_detail()
         
         if model_cls:
             self._detail_cache = model_cls._default_manager.using(self._state.db).get(order__id__exact=self.id)
             self._detail_cache.order = self
         else:
             self._detail_cache = None
     return self._detail_cache
 def total(self):
     total = sum(line.price for line in self.orderline_set.all()) + self.shipping_cost
     
     detail_cls = helpers.get_order_detail()
     if detail_cls:
         try:
             detail = self.get_detail()
         except detail_cls.DoesNotExist:
             pass
         else:
             total += getattr(detail, 'additional_total', lambda: 0)()
             
     return total
Exemple #3
0
def checkout_form_factory():
    """Returns a form corresponding to a subset of the ORDER_DETAIL_MODEL, if 
       one is specified and CHECKOUT_FORM_FIELDS is set. Otherwise returns a 
       dummy form."""
    
    order_detail_cls = helpers.get_order_detail()
    
    if order_detail_cls and cart_settings.CHECKOUT_FORM_FIELDS:
        class CheckoutForm(forms.ModelForm):
            class Meta:
                model = order_detail_cls
                fields = cart_settings.CHECKOUT_FORM_FIELDS
        
        return CheckoutForm
    else:
        class DummyForm(forms.Form):
            def update(self, cart):
                pass
        return DummyForm
Exemple #4
0
def order_detail_form_factory():
    """Returns a form for the extra custom details defined in ORDER_DETAIL_MODEL.
       Excludes those displayed in the checkout via CHECKOUT_FORM_FIELDS."""
    
    form_cls = helpers.get_order_detail_form()
    if form_cls:
        return form_cls
    else:
        model_cls = helpers.get_order_detail()
        if model_cls:
            class OrderDetailForm(forms.ModelForm):
                class Meta:
                    model = model_cls
                    exclude = ['order'] + (cart_settings.CHECKOUT_FORM_FIELDS)
            return OrderDetailForm
        else:
            # dummy form class with no fields, to simplify the view
            class DummyForm(forms.Form):
                def __init__(self, *args, **kwargs):
                    kwargs.pop('instance', None)
                    super(DummyForm, self).__init__(*args, **kwargs)
            return DummyForm
            if order.product not in products:
                products.append(order.product)
            
        return ', '.join([unicode(p) for p in products])

    
    def shipped(self, instance):
        if instance.completion_date:
            return datetime.datetime.strftime(instance.completion_date, '%Y-%m-%d')
        else:
            return 'N/A'
    shipped.admin_order_field = 'completion_date'

    def set_status_to_shipped(self, request, queryset):
        for item in queryset.all():
            item.status = 'shipped'
            item.save()

order_detail = helpers.get_order_detail()
if order_detail:
    class ExtraDetailInline(admin.StackedInline):
        model = order_detail
        max_num = 1
        extra = 1
    
    OrderAdmin.inlines = [ExtraDetailInline] + OrderAdmin.inlines

admin.site.register(Order, OrderAdmin)


Exemple #6
0
def delivery(request):
    """Collects standard delivery information, along with any extra information
       from the order_detail model."""
    
    cart = helpers.get_cart()(request)
    
    order_form_cls = helpers.get_order_form()
    detail_cls = helpers.get_order_detail()
    
    if not validate_cart(request, 'delivery'):
        return HttpResponseRedirect(reverse(checkout))
    else:
        try:
            instance = Order.objects.get(pk=cart.data.get('order_pk', None))
            if detail_cls:
                try:
                    detail_instance = instance.get_detail()
                except detail_cls.DoesNotExist:
                    detail_instance = None
            else:
                detail_instance = None
        except Order.DoesNotExist:
            instance = None
            detail_instance = None
        
        # get detail form, or dummy form if no ORDER_DETAIL_MODEL defined
        detail_form_cls = order_detail_form_factory()
        
        form_kwargs = {'label_suffix': '', 'instance': instance, 'initial': cart.data}
        detail_form_kwargs = {'label_suffix': '', 'instance': detail_instance, 'initial': cart.detail_data, 'prefix': 'detail'}
        
        
        if request.POST:
            form = order_form_cls(request.POST, **form_kwargs)
            detail_form = detail_form_cls(request.POST, **detail_form_kwargs)
            valid = form.is_valid() and detail_form.is_valid()
            if valid:
                order = form.save(commit=False)
                order.session_id = request.session.session_key
                order.shipping_cost = cart.shipping_cost()
                
                # save needed here to create the primary key
                order.save()
                
                for line in order.orderline_set.all():
                    line.delete()
                for item in cart:
                    order.orderline_set.create(
                        product=item.product,
                        quantity=item['quantity'],
                        price=item.row_total(),
                        options=simplejson.dumps(item['options'])
                    )
                
                
                # if the form has no 'save' method, assume it's the dummy form
                if callable(getattr(detail_form, 'save', None)):
                    # the detail object may have been created on order save, so check for that
                    if detail_cls:
                        try:
                            detail_form.instance = order.get_detail()
                        except detail_cls.DoesNotExist:
                            pass
                        
                    detail = detail_form.save(commit=False)
                    detail.order = order # in case it is being created for the first time
                    for field in cart_settings.CHECKOUT_FORM_FIELDS:
                        setattr(detail, field, cart.detail_data[field])
                    detail.save()
                
                # confirmed status can trigger notifications etc, so don't set it until all
                # order info is in the database
                order.status = 'confirmed'
                order.save()
               
                cart.update_data({'order_pk': order.pk})
                cart.modified()
                
                redirect_url = reverse('cart.views.payment', args=(order.hash,))
            else:
                redirect_url = None
                
            if request.is_ajax():
                html = render_to_string(
                    'cart/delivery_ajax.html',
                    RequestContext(request, {
                        'cart': cart,
                        'form': form,
                        'detail_form': detail_form,
                        'steps': steps(request),
                        'current_step': 2,
                    })
                )
                    
                return HttpResponse(simplejson.dumps({
                    'success': valid,
                    'cart': cart.as_dict(),
                    'redirect_url': redirect_url,
                    'hard_redirect': True,
                    'html': html,
                }), mimetype='application/json')

            elif valid:
                return HttpResponseRedirect(redirect_url)
                
        else:
            form = order_form_cls(**form_kwargs)
            detail_form = detail_form_cls(**detail_form_kwargs)
    
    
        return render_to_response(
            'cart/delivery.html', 
            RequestContext(request, {
                'cart': cart,
                'form': form,
                'detail_form': detail_form,
                'steps': steps(request),
                'current_step': 2,
            })
        )