Exemplo n.º 1
0
def moneyfmt(val, currency_code=None, wrapcents="", places=None):
    """Formats val according to the currency settings for the desired currency, as set in L10N_SETTINGS"""
    if val is None or val == "":
        val = Decimal("0")

    currencies = get_l10n_setting("currency_formats")
    currency = None

    if currency_code:
        currency = currencies.get(currency_code, None)
        if not currency:
            log.warn(
                'Could not find currency code definitions for "%s", please look at l10n.l10n_settings for examples.'
            )

    if not currency:
        default_currency_code = get_l10n_setting("default_currency", None)

        if not default_currency_code:
            log.fatal("No default currency code set in L10N_SETTINGS")
            raise ImproperlyConfigured("No default currency code set in L10N_SETTINGS")

        if currency_code == default_currency_code:
            raise ImproperlyConfigured(
                "Default currency code '%s' not found in currency_formats in L10N_SETTINGS", currency_code
            )

        return moneyfmt(val, currency_code=default_currency_code, wrapcents=wrapcents, places=places)

    # here we are assured we have a currency format

    if val >= 0:
        key = "positive"
    else:
        val = abs(val)
        key = "negative"

    # If we've been passed places, modify the format to use the new value
    if places is None or places == "":
        fmt = currency[key]
    else:
        start_fmt = currency[key]
        fmt_parts = re.split(decimal_fmt, start_fmt)
        new_decimal = u".%sf" % places
        # We need to keep track of all 3 parts because we might want to use
        # () to denote a negative value and don't want to lose the trailing )
        fmt = u"".join([fmt_parts[0], new_decimal, fmt_parts[2]])
    formatted = fmt % {"val": val}

    sep = currency.get("decimal", ".")
    if sep != ".":
        formatted = decimal_separator.sub(r"\1%s\2" % sep, formatted)

    if wrapcents:
        pos = formatted.rfind(sep)
        if pos > -1:
            pos += 1
            formatted = u"%s<%s>%s</%s>" % (formatted[:pos], wrapcents, formatted[pos:], wrapcents)

    return formatted
Exemplo n.º 2
0
def moneyfmt(val, currency_code=None, wrapcents='', places=None):
    """Formats val according to the currency settings for the desired currency, as set in L10N_SETTINGS"""
    if val is None or val == '':
       val = Decimal('0')

    currencies = get_l10n_setting('currency_formats')
    currency = None

    if currency_code:
        currency = currencies.get(currency_code, None)
        if not currency:
            log.warn('Could not find currency code definitions for "%s", please look at l10n.l10n_settings for examples.')

    if not currency:
        default_currency_code = get_l10n_setting('default_currency', None)

        if not default_currency_code:
            log.fatal("No default currency code set in L10N_SETTINGS")
            raise ImproperlyConfigured("No default currency code set in L10N_SETTINGS")

        if currency_code == default_currency_code:
            raise ImproperlyConfigured("Default currency code '%s' not found in currency_formats in L10N_SETTINGS", currency_code)

        return moneyfmt(val, currency_code=default_currency_code, wrapcents=wrapcents, places=places)

    # here we are assured we have a currency format

    if val>=0:
        key = 'positive'
    else:
        val = abs(val)
        key = 'negative'
    
    # If we've been passed places, modify the format to use the new value
    if places is None or places == '':
        fmt = currency[key]
    else:
        start_fmt = currency[key]
        fmt_parts = re.split(decimal_fmt, start_fmt)
        new_decimal = ".%sf" % places
        # We need to keep track of all 3 parts because we might want to use
        # () to denote a negative value and don't want to lose the trailing )
        fmt = ''.join([fmt_parts[0], new_decimal, fmt_parts[2]])
    formatted = fmt % { 'val' : val }

    sep = currency.get('decimal', '.')
    if sep != '.':
        formatted = decimal_separator.sub(r'\1%s\2' % sep, formatted)

    if wrapcents:
        pos = formatted.rfind(sep)
        if pos>-1:
            pos +=1
            formatted = "%s<%s>%s</%s>" % (formatted[:pos], wrapcents, formatted[pos:], wrapcents)

    return formatted
Exemplo n.º 3
0
def satchmo_language_selection_form(context):
    """
    Display the set language form, if enabled in shop settings.
    """
    request = threadlocals.get_current_request()
    enabled = get_l10n_setting('allow_translation_choice')
    languages = []
    if enabled:
        try:
            url = urlresolvers.reverse('satchmo_set_language')
            languages = settings.LANGUAGES
            print "111"
        except urlresolvers.NoReverseMatch:
            url = ""
            log.warning(
                'No url found for satchmo_set_language (OK if running tests)')
            print "112"

    else:
        url = ""

    return {
        'enabled': enabled,
        'set_language_url': url,
        'languages': languages,
        'STATIC_URL': context.get('STATIC_URL', ''),  # for easy flag images
        'django_language': request.session.get('django_language', 'en'),
    }
Exemplo n.º 4
0
class CategoryOptions(admin.ModelAdmin):

    if config_value('SHOP', 'SHOW_SITE'):
        list_display = ('site', )
    else:
        list_display = ()

    list_display += ('name', '_parents_repr', 'is_active')
    list_display_links = ('name', )
    ordering = ['site', 'parent__id', 'ordering', 'name']
    inlines = [CategoryAttributeInline, CategoryImage_Inline]
    if get_l10n_setting('show_admin_translations'):
        inlines.append(CategoryTranslation_Inline)
    filter_horizontal = ('related_categories', )
    form = CategoryAdminForm

    actions = ('mark_active', 'mark_inactive')

    def mark_active(self, request, queryset):
        queryset.update(is_active=True)
        return HttpResponseRedirect('')

    def mark_inactive(self, request, queryset):
        queryset.update(is_active=False)
        return HttpResponseRedirect('')
Exemplo n.º 5
0
Arquivo: satchmo_util.py Projeto: 34/T
def satchmo_language_selection_form(context):
    """
    Display the set language form, if enabled in shop settings.
    """
    request = threadlocals.get_current_request()
    enabled = get_l10n_setting('allow_translation_choice')
    languages = []
    if enabled:
        try:
            url = urlresolvers.reverse('satchmo_set_language')
            languages = settings.LANGUAGES

        except urlresolvers.NoReverseMatch:
            url = ""
            log.warning('No url found for satchmo_set_language (OK if running tests)')

    else:
        url = ""

    media_url = context.get('media_url', None)
    return {
        'enabled' : enabled,
        'set_language_url' : url,
        'languages' : languages,
        'media_url' : media_url,
        'django_language' : request.session.get('django_language', 'en'),
    }
Exemplo n.º 6
0
def satchmo_language_selection_form(context):
    """
    Display the set language form, if enabled in shop settings.
    """
    request = threadlocals.get_current_request()
    enabled = get_l10n_setting("allow_translation_choice")
    languages = []
    if enabled:
        try:
            url = urlresolvers.reverse("satchmo_set_language")
            languages = settings.LANGUAGES
            print "111"
        except urlresolvers.NoReverseMatch:
            url = ""
            log.warning("No url found for satchmo_set_language (OK if running tests)")
            print "112"

    else:
        url = ""

    return {
        "enabled": enabled,
        "set_language_url": url,
        "languages": languages,
        "STATIC_URL": context.get("STATIC_URL", ""),  # for easy flag images
        "django_language": request.session.get("django_language", "en"),
    }
Exemplo n.º 7
0
def moneyfmt(val, currency_code=None, wrapcents=''):
    """Formats val according to the currency settings for the desired currency, as set in L10N_SETTINGS"""
    if val is None or val == '':
       val = Decimal('0')

    currencies = get_l10n_setting('currency_formats')
    currency = None

    if currency_code:
        currency = currencies.get(currency_code, None)
        if not currency:
            log.warn('Could not find currency code definitions for "%s", please look at l10n.l10n_settings for examples.')

    if not currency:
        default_currency_code = get_l10n_setting('default_currency', None)

        if not default_currency_code:
            log.fatal("No default currency code set in L10N_SETTINGS")
            raise ImproperlyConfigured("No default currency code set in L10N_SETTINGS")

        if currency_code == default_currency_code:
            raise ImproperlyConfigured("Default currency code '%s' not found in currency_formats in L10N_SETTINGS", currency_code)

        return moneyfmt(val, currency_code=default_currency_code, wrapcents=wrapcents)

    # here we are assured we have a currency format

    if val>=0:
        key = 'positive'
    else:
        val = abs(val)
        key = 'negative'

    fmt = currency[key]
    formatted = fmt % { 'val' : val }

    sep = currency.get('decimal', '.')
    if sep != '.':
        formatted = decimal_separator.sub(r'\1%s\2' % sep, formatted)

    if wrapcents:
        pos = formatted.rfind(sep)
        if pos>-1:
            pos +=1
            formatted = u"%s<%s>%s</%s>" % formatted[:pos], wrapcents, formatted[pos:], wrapcents

    return formatted
Exemplo n.º 8
0
class OptionGroupOptions(admin.ModelAdmin):
    inlines = [Option_Inline]
    if get_l10n_setting('show_admin_translations'):
        inlines.append(OptionGroupTranslation_Inline)
    if config_value('SHOP', 'SHOW_SITE'):
        list_display = ('site', )
    else:
        list_display = ()
    list_display += ('name', )
Exemplo n.º 9
0
    def testFake(self):
        currencies = l10n_settings.get_l10n_setting('currency_formats')
        currencies['FAKE'] = {'symbol': '^ ', 'positive' : "%(val)0.2f ^", 'negative': "(%(val)0.2f) ^", 'decimal' : ','}
        
        l10n_settings.set_l10n_setting('currency_formats', currencies)
        
        val = Decimal('10.00')
        self.assertEqual(moneyfmt(val, currency_code='FAKE'), '10,00 ^')

        val = Decimal('-50.00')
        self.assertEqual(moneyfmt(val, currency_code='FAKE'), '(50,00) ^')
Exemplo n.º 10
0
Arquivo: tests.py Projeto: 34/T
    def testFake(self):
        currencies = l10n_settings.get_l10n_setting('currency_formats')
        currencies['FAKE'] = {'symbol': '^ ', 'positive' : "%(val)0.2f ^", 'negative': "(%(val)0.2f) ^", 'decimal' : ','}
        
        l10n_settings.set_l10n_setting('currency_formats', currencies)
        
        val = Decimal('10.00')
        self.assertEqual(moneyfmt(val, currency_code='FAKE'), '10,00 ^')

        val = Decimal('-50.00')
        self.assertEqual(moneyfmt(val, currency_code='FAKE'), '(50,00) ^')
Exemplo n.º 11
0
class OptionGroupOptions(admin.ModelAdmin):
    inlines = [Option_Inline]
    if get_l10n_setting('show_admin_translations'):
        inlines.append(OptionGroupTranslation_Inline)
    if config_value('SHOP', 'SHOW_SITE'):
        list_display = ('which_site', )
    else:
        list_display = ()
    list_display += ('name', )
    filter_horizontal = ('site', )

    def which_site(self, obj):
        return ', '.join(site.name for site in obj.site.all().order_by())

    which_site.short_description = 'Site'
Exemplo n.º 12
0
class ProductOptions(admin.ModelAdmin):
    def make_active(self, request, queryset):
        rows_updated = queryset.update(active=True)
        if rows_updated == 1:
            message_bit = _("1 product was")
        else:
            message_bit = _("%s products were" % rows_updated)
        self.message_user(request,
                          _("%s successfully marked as active") % message_bit)
        return HttpResponseRedirect('')

    make_active.short_description = _("Mark selected products as active")

    def make_inactive(self, request, queryset):
        rows_updated = queryset.update(active=False)
        if rows_updated == 1:
            message_bit = _("1 product was")
        else:
            message_bit = _("%s products were" % rows_updated)
        self.message_user(
            request,
            _("%s successfully marked as inactive") % message_bit)
        return HttpResponseRedirect('')

    make_inactive.short_description = _("Mark selected products as inactive")

    def make_featured(self, request, queryset):
        rows_updated = queryset.update(featured=True)
        if rows_updated == 1:
            message_bit = _("1 product was")
        else:
            message_bit = _("%s products were" % rows_updated)
        self.message_user(
            request,
            _("%s successfully marked as featured") % message_bit)
        return HttpResponseRedirect('')

    make_featured.short_description = _("Mark selected products as featured")

    def make_unfeatured(self, request, queryset):
        rows_updated = queryset.update(featured=False)
        if rows_updated == 1:
            message_bit = _("1 product was")
        else:
            message_bit = _("%s products were" % rows_updated)
        self.message_user(
            request,
            _("%s successfully marked as not featured") % message_bit)
        return HttpResponseRedirect('')

    make_unfeatured.short_description = _(
        "Mark selected products as not featured")

    def formatted_price(self, obj):
        """Format the price in the list_display so that the currency symbol shows
        """
        return moneyfmt(obj.unit_price)

    formatted_price.short_description = _("Unit price")

    def formatted_inventory(self, obj):
        """Format the inventory in the list_display so that 1.00000 becomes 1
        but 1.0002 still shows as 1.0002
        """
        return obj.items_in_stock.normalize()

    formatted_inventory.short_description = _("Number in stock")
    formatted_inventory.admin_order_field = "items_in_stock"

    if config_value('SHOP', 'SHOW_SITE'):
        list_display = ('site', )
    else:
        list_display = ()

    list_display += ('slug', 'name', 'formatted_price', 'formatted_inventory',
                     'active', 'featured', 'get_subtypes')
    list_display_links = ('slug', 'name')
    list_filter = ('category', 'date_added', 'active', 'featured')
    actions = ('make_active', 'make_inactive', 'make_featured',
               'make_unfeatured')
    fieldsets = (
        (None, {
            'fields':
            ('site', 'category', 'name', 'slug', 'sku', 'description',
             'short_description', 'date_added', 'active', 'featured',
             'items_in_stock', 'total_sold', 'ordering', 'shipclass')
        }),
        (_('Meta Data'), {
            'fields': ('meta', ),
            'classes': ('collapse', )
        }),
        (_('Item Dimensions'), {
            'fields': (('length', 'length_units', 'width', 'width_units',
                        'height', 'height_units'), ('weight', 'weight_units')),
            'classes': ('collapse', )
        }),
        (_('Tax'), {
            'fields': ('taxable', 'taxClass'),
            'classes': ('collapse', )
        }),
        (_('Related Products'), {
            'fields': ('related_items', 'also_purchased'),
            'classes': ('collapse', )
        }),
    )
    search_fields = ['slug', 'sku', 'name']
    inlines = [ProductAttribute_Inline, Price_Inline, ProductImage_Inline]
    if get_l10n_setting('show_admin_translations'):
        inlines.append(ProductTranslation_Inline)
    filter_horizontal = ('category', )

    def formfield_for_dbfield(self, db_field, **kwargs):
        field = super(ProductOptions,
                      self).formfield_for_dbfield(db_field, **kwargs)
        fieldname = db_field.name
        if fieldname in ("length_units", "width_units", "height_units"):
            field.initial = default_dimension_unit()
        elif fieldname == "weight_units":
            field.initial = default_weight_unit()
        return field
Exemplo n.º 13
0
class OptionOptions(admin.ModelAdmin):
    inlines = []
    if get_l10n_setting('show_admin_translations'):
        inlines.append(OptionTranslation_Inline)
Exemplo n.º 14
0
class CustomTextFieldOptions(admin.ModelAdmin):
    inlines = []
    if get_l10n_setting('show_admin_translations'):
        inlines.append(CustomTextFieldTranslation_Inline)