def __unicode__(self): return u"{title} - {location} ({start} - {end})".format( title=self.topic.title, location=self.location.name, start=localize(self.starting_time), end=localize(self.ending_time), )
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(timezone.template_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field, models.FileField) and value: return mark_safe('<a href="%s">%s</a>' % ( conditional_escape(value.url), conditional_escape(value), )) else: return smart_text(value)
def show(self, width = 640, height = 390, _cls = "" ): if self.show_title: title = self.title else: title = "" html =' <div class="movie {ccls}">'.format(ccls = _cls) html += """ <div class="title">{title}</div> <div class="clearer"></div> <div class="movie_object"> <iframe width="{width}" height="{height}" src="{url}?wmode=opaque" frameborder="0" allowfullscreen></iframe> </div> """.format( title = title, url = self.url, width = width, height = height, ) if self.show_author and self.author: html += '<div class="author">Autor: %s</div>' %self.author if self.show_date and localize( self.publish_date ) : html += '<div class="date">%s</div>' %localize( self.publish_date ) html +='<div class="clearer"></div>' if self.show_description and self.description : html += '<div class="description">%s</div>' %self.description html += '</div>' return mark_safe( html )
def display_for_field(value, field): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): decimal_places = field.decimal_places if decimal_places: point_pos = str(value).rfind('.') if point_pos != -1: # not integer removing_trailing_zeros = str(value).rstrip('0') decimal_places = len(removing_trailing_zeros) - point_pos - 1 else: # integer decimal_places = 0 return formats.number_format(value, decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_text(obj) for obj in value.all()]) else: return smart_text(value)
def catalog_edit(request): id = request.GET.get('id') item = get_object_or_404(CatalogItem, pk=id, owner=request.user) response = {'error': 'ko'} if request.POST: form = CatalogForm(request.POST, instance=item) form.fields['section_label'].required = False if form.is_valid(): item = form.save() response['error'] = 'ok' response['id'] = item.id response['label'] = item.label response['category'] = item.category response['category_label'] = item.get_category_display() response['unit_price'] = localize(item.unit_price) response['vat_rate'] = localize(item.vat_rate) or '' response['vat_rate_label'] = item.get_vat_rate_display() or '' response['section'] = item.section.id response['section_label'] = unicode(item.section) else: response['error_msg'] = [] for key, msg in form.errors.items(): response['error_msg'].append("%s : %s" % (unicode(form[key].label), " ".join(msg))) return HttpResponse(simplejson.dumps(response), mimetype='application/javascript')
def djmoney_display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE try: if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(timezone.localtime(value)) elif isinstance(field, models.DateField) or isinstance(field, models.TimeField): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) else: return smart_unicode(value) except: return smart_unicode(value)
def show(self, photos_no = 4 , _cls = ""): photos = self.photos.all().order_by( "-publish_date" )[:photos_no] width = 200 * len( photos ) html = '<div class="gallery short %s" ><div class="title">' % _cls if self.show_title and self.title : html += self.title html += '</div>' html +='<div class="list" style="width:%dpx;margin-left:auto;margin-right:auto;">' % width for photo in photos: src = unicode( photo.image ) html += '<a rel="prettyPhoto[pp_gal]" title="{description}" href="/media/{image}" ><img src="/media/thumbnails/{image}" /></a>'\ .format( description = photo.description, image = src ) html +='<div class="clearer"></div>' html += '</div>' if self.photos.count() > photos_no: html += '<a href="/gallery,%d,%s.html" class="more">Zobacz całą galerię.</a>' % ( self.id, "galeria" ) html +='<div class="clearer"></div>' if self.show_description and self.description: html += '<div class="description">%s</div>' %self.description if self.show_author and self.author : html += '<div class="author">Autor: %s</div>' %self.author if self.show_date and self.publish_date: html += '<div class="date">%s</div>' % localize( localize( self.publish_date ) ) html +='<div class="clearer"></div>' html += "</div>" return mark_safe( html )
def catalog_add(request): response = {'error': 'ko'} if request.POST: form = CatalogForm(request.POST) if form.is_valid(): item = form.save(commit=False) section, created = CatalogSection.objects.get_or_create(name=form.cleaned_data.get('section_label'), owner=request.user, defaults={'name': form.cleaned_data.get('section_label'), 'owner': request.user}) item.section = section item.owner = request.user item.save() response['error'] = 'ok' response['id'] = item.id response['label'] = item.label response['category'] = item.category response['category_label'] = item.get_category_display() response['unit_price'] = localize(item.unit_price) response['vat_rate'] = localize(item.vat_rate) or '' response['vat_rate_label'] = item.get_vat_rate_display() or '' response['section'] = item.section.id response['section_label'] = unicode(item.section) else: response['error_msg'] = [] for key, msg in form.errors.items(): response['error_msg'].append("%s : %s" % (unicode(form[key].label), " ".join(msg))) return HttpResponse(simplejson.dumps(response), mimetype='application/javascript')
def __unicode__(self): if self.floor > 0 and self.ceiling > 0: return u'%s m² - %s m²'%(localize(self.floor), localize(self.ceiling)) elif self.floor > 0: return u'> %s m²'%(localize(self.floor), ) else: return u'< %s m²'%(localize(self.ceiling), )
def _display_order_changed(event: Event, logentry: LogEntry): data = json.loads(logentry.data) text = _('The order has been changed:') if logentry.action_type == 'pretix.event.order.changed.item': old_item = str(event.items.get(pk=data['old_item'])) if data['old_variation']: old_item += ' - ' + str(event.itemvariations.get(pk=data['old_variation'])) new_item = str(event.items.get(pk=data['new_item'])) if data['new_variation']: new_item += ' - ' + str(event.itemvariations.get(pk=data['new_variation'])) return text + ' ' + _('{old_item} ({old_price} {currency}) changed to {new_item} ({new_price} {currency}).').format( old_item=old_item, new_item=new_item, old_price=formats.localize(Decimal(data['old_price'])), new_price=formats.localize(Decimal(data['new_price'])), currency=event.currency ) elif logentry.action_type == 'pretix.event.order.changed.price': return text + ' ' + _('Price of a position changed from {old_price} {currency} to {new_price} {currency}.').format( old_price=formats.localize(Decimal(data['old_price'])), new_price=formats.localize(Decimal(data['new_price'])), currency=event.currency ) elif logentry.action_type == 'pretix.event.order.changed.cancel': old_item = str(event.items.get(pk=data['old_item'])) if data['old_variation']: old_item += ' - ' + str(ItemVariation.objects.get(pk=data['old_variation'])) return text + ' ' + _('{old_item} ({old_price} {currency}) removed.').format( old_item=old_item, old_price=formats.localize(Decimal(data['old_price'])), currency=event.currency )
def display_for_field(value, field): from xadmin.defs import EMPTY_CHANGELIST_VALUE if field.flatchoices: if hasattr(value,'__iter__'): rets = [ dict(field.flatchoices).get(e, EMPTY_CHANGELIST_VALUE) for e in value] return ','.join(rets) else: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_unicode(obj) for obj in value.all()]) else: return smart_unicode(value)
def display_for_field(value, field , **kwargs): from xadmin.views.list import EMPTY_CHANGELIST_VALUE from xadmin.fields import ColorField, ImageWithThumbField if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_text(obj) for obj in value.all()]) elif isinstance(field, ColorField): return collor_field(value) elif isinstance(field, ImageWithThumbField): return image_field(value, field, **kwargs) else: return smart_text(value)
def import_proposal_line(line, context): content_kind = unicode(line.content_kind) if content_kind == '' and not hasattr(line, 'total_price'): content_kind = 'comment' if hasattr(line, 'description_more'): description_more = unicode(line.description_more).strip() else: description_more = '' if content_kind == 'total': total = context.current_total() description = u'Total: {} €\n'.format(localize(total)) context.start_group() elif content_kind == 'comment': description = unicode(line.description).strip() if description: description = '*' + description + '*' if description_more: description += '\n' + description_more else: # Normal lines + options description = unicode(line.description).strip() description = '- ' + description if content_kind == 'option': description += ' ' + OPTIONAL_MISSION_SUFFIX if description_more: description += '. ' + description_more if hasattr(line, 'unit_price') and hasattr(line, 'quantity'): # This is a product proposal line with an attached price unit_price = Decimal(unicode(line.unit_price)) unit = unicode(line.unit) if unit: unit = ' ' + unit quantity = Decimal(unicode(line.quantity)) # Do not use line.total_price: it is set to 0 for options total_price = unit_price * quantity description += '. ' if quantity == 1: description += u'{} €'.format(localize(total_price)) else: description += u'{}{} × {} € = {} €'.format( quantity, unit, localize(unit_price), localize(total_price)) if not content_kind == 'option': context.add_to_current_total(total_price) return description
def test_l10n_disabled(self): """ Catalan locale with format i18n disabled translations will be used, but not formats """ settings.USE_L10N = False activate('ca') try: self.assertEqual('N j, Y', get_format('DATE_FORMAT')) self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual('.', get_format('DECIMAL_SEPARATOR')) self.assertEqual(u'10:15 a.m.', time_format(self.t)) self.assertEqual(u'des. 31, 2009', date_format(self.d)) self.assertEqual(u'desembre 2009', date_format(self.d, 'YEAR_MONTH_FORMAT')) self.assertEqual(u'12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT')) self.assertEqual('No localizable', localize('No localizable')) self.assertEqual(decimal.Decimal('66666.666'), localize(self.n)) self.assertEqual(99999.999, localize(self.f)) self.assertEqual(datetime.date(2009, 12, 31), localize(self.d)) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), localize(self.dt)) self.assertEqual(u'66666.666', Template('{{ n }}').render(self.ctxt)) self.assertEqual(u'99999.999', Template('{{ f }}').render(self.ctxt)) self.assertEqual(u'2009-12-31', Template('{{ d }}').render(self.ctxt)) self.assertEqual(u'2009-12-31 20:50:00', Template('{{ dt }}').render(self.ctxt)) self.assertEqual(u'66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual(u'100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) self.assertEqual(u'10:15 a.m.', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)) self.assertEqual(u'12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual(u'12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt)) form = I18nForm({ 'decimal_field': u'66666,666', 'float_field': u'99999,999', 'date_field': u'31/12/2009', 'datetime_field': u'31/12/2009 20:50', 'time_field': u'20:50', 'integer_field': u'1.234', }) self.assertEqual(False, form.is_valid()) self.assertEqual([u'Introdu\xefu un n\xfamero.'], form.errors['float_field']) self.assertEqual([u'Introdu\xefu un n\xfamero.'], form.errors['decimal_field']) self.assertEqual([u'Introdu\xefu una data v\xe0lida.'], form.errors['date_field']) self.assertEqual([u'Introdu\xefu una data/hora v\xe0lides.'], form.errors['datetime_field']) self.assertEqual([u'Introdu\xefu un n\xfamero sencer.'], form.errors['integer_field']) form2 = SelectDateForm({ 'date_field_month': u'12', 'date_field_day': u'31', 'date_field_year': u'2009' }) self.assertEqual(True, form2.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form2.cleaned_data['date_field']) self.assertEqual( u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>', SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) finally: deactivate()
def _raw_to_verbose(self, raw): verbose = raw if isinstance(raw, bool): verbose = raw and ugettext('yes') or ugettext('no') elif isinstance(raw, datetime.datetime): verbose = formats.localize(timezone.template_localtime(raw)) elif isinstance(raw, (datetime.date, datetime.time)): verbose = formats.localize(raw) return verbose
def test_l10n_disabled(self): """ Catalan locale with format i18n disabled translations will be used, but not formats """ settings.USE_L10N = False activate("ca") try: self.assertEqual("N j, Y", get_format("DATE_FORMAT")) self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) self.assertEqual(u"10:15 a.m.", time_format(self.t)) self.assertEqual(u"des. 31, 2009", date_format(self.d)) self.assertEqual(u"desembre 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) self.assertEqual(u"12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT")) self.assertEqual("No localizable", localize("No localizable")) self.assertEqual(decimal.Decimal("66666.666"), localize(self.n)) self.assertEqual(99999.999, localize(self.f)) self.assertEqual(datetime.date(2009, 12, 31), localize(self.d)) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), localize(self.dt)) self.assertEqual(u"66666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual(u"99999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual(u"2009-12-31", Template("{{ d }}").render(self.ctxt)) self.assertEqual(u"2009-12-31 20:50:00", Template("{{ dt }}").render(self.ctxt)) self.assertEqual(u"66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt)) self.assertEqual(u"100000.0", Template("{{ f|floatformat }}").render(self.ctxt)) self.assertEqual(u"10:15 a.m.", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)) self.assertEqual(u"12/31/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual( u"12/31/2009 8:50 p.m.", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt) ) form = I18nForm( { "decimal_field": u"66666,666", "float_field": u"99999,999", "date_field": u"31/12/2009", "datetime_field": u"31/12/2009 20:50", "time_field": u"20:50", } ) self.assertEqual(False, form.is_valid()) self.assertEqual([u"Introdu\xefu un n\xfamero."], form.errors["float_field"]) self.assertEqual([u"Introdu\xefu un n\xfamero."], form.errors["decimal_field"]) self.assertEqual([u"Introdu\xefu una data v\xe0lida."], form.errors["date_field"]) self.assertEqual([u"Introdu\xefu una data/hora v\xe0lides."], form.errors["datetime_field"]) form2 = SelectDateForm({"date_field_month": u"12", "date_field_day": u"31", "date_field_year": u"2009"}) self.assertEqual(True, form2.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form2.cleaned_data["date_field"]) self.assertEqual( u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>', SelectDateWidget(years=range(2009, 2019)).render("mydate", datetime.date(2009, 12, 31)), ) finally: deactivate()
def changelist_view(self, request, extra_context=None): # First load a mapping between config name and default value if not self.has_change_permission(request, None): raise PermissionDenied default_initial = ((name, values[0]) for name, values in settings.CONFIG.items()) # Then update the mapping with actually values from the backend initial = dict(default_initial, **dict(config._backend.mget(settings.CONFIG.keys()))) form = ConstanceForm(initial=initial) if request.method == 'POST': form = ConstanceForm(data=request.POST, initial=initial) if form.is_valid(): form.save() # In django 1.5 this can be replaced with self.message_user messages.add_message( request, messages.SUCCESS, _('Live settings updated successfully.'), ) return HttpResponseRedirect('.') context = { 'config_values': {}, 'title': _('Constance config'), 'app_label': 'constance', 'opts': Config._meta, 'form': form, 'media': self.media + form.media, } for name, values in settings.CONFIG.items(): default = values[0] help_text = values[1] if len(values)==3: type_item = values[2] else: type_item = _('Default') # First try to load the value from the actual backend value = initial.get(name) # Then if the returned value is None, get the default if value is None: value = getattr(config, name) if type_item not in context['config_values']: context['config_values'][type_item] = [] context['config_values'][type_item].append({ 'name': name, 'default': localize(default), 'help_text': _(help_text), 'value': localize(value), 'modified': value != default, 'form_field': form[name], }) # context['config_values'].sort(key=itemgetter('name')) request.current_app = self.admin_site.name # compatibility to be removed when 1.7 is deprecated extra = {'current_app': self.admin_site.name} if VERSION < (1, 8) else {} return TemplateResponse(request, self.change_list_template, context, **extra)
def localize_duration(start, end): ret = [] if start.date() == end.date(): ret.append(localize(start.date())) ret.append(_('from %s') % localize(start.time())) ret.append(_('to %s') % localize(end.time())) else: ret.append(_('from %s') % localize(start)) ret.append(_('to %s') % localize(end)) return ' '.join(ret)
def add_rows(self, rows): row_count = 0 extra_rows = 0 extra_style = [] data = [] data.append([ugettext('Label'), ugettext('Quantity'), ugettext('Unit price'), ugettext('Total excl tax')]) if self.user.get_profile().vat_number: data[0].append(ugettext('VAT')) label_width = 4.0 * inch else: label_width = 4.5 * inch for row in rows: row_count += 1 label = self.get_label(row) #label = label.replace('&', '[et]') para = Paragraph(force_escape(label), ProposalTemplate.styleLabel) para.width = label_width splitted_para = para.breakLines(label_width) label = self.get_splitted_content(splitted_para.lines[0]) quantity = row.quantity quantity = quantity.quantize(Decimal(1)) if quantity == quantity.to_integral() else quantity.normalize() unit_price = row.unit_price unit_price = unit_price.quantize(Decimal(1)) if unit_price == unit_price.to_integral() else unit_price.normalize() total = row.quantity * row.unit_price total = total.quantize(Decimal(1)) if total == total.to_integral() else total.normalize() data_row = [label, localize(quantity), "%s %s" % (localize(unit_price), "€".decode('utf-8')), "%s %s" % (localize(total), "€".decode('utf-8'))] if self.user.get_profile().vat_number: if row.vat_rate: data_row.append("%s%%" % (localize(row.vat_rate))) else: data_row.append('-') data.append(data_row) for extra_row in splitted_para.lines[1:]: label = self.get_splitted_content(extra_row) if self.user.get_profile().vat_number: data.append([label, '', '', '', '']) else: data.append([label, '', '', '']) extra_rows += 1 extra_detail_rows = self.add_row_detail(data, row, label_width) if extra_detail_rows: extra_style.append(('FONT', (0, row_count + extra_rows + 1), (0, row_count + extra_rows + extra_detail_rows), self.styleDetail.fontName)) extra_style.append(('TEXTCOLOR', (0, row_count + extra_rows + 1), (0, row_count + extra_rows + extra_detail_rows), self.styleDetail.textColor)) extra_rows += extra_detail_rows self.add_row_table(data, row_count + extra_rows, extra_style) self.story.append(Spacer(self.doc.width, self.space_before_footer))
def local_dateformat(dt): """ Returns a string representation of the given ``datetime`` ``dt``. """ if formats: try: return formats.localize(dt, use_l10n=True) except TypeError: # Django 1.2 return formats.localize(dt) return dateformat.format(dt, get_date_formats()[1])
def highlighted_due_date(self): if self.is_overdue(): return format_html( '<span style="background: red;">{}</span>', formats.localize(self.due_date)) elif (self.due_date - timezone.now().date()) < timedelta(days=2): return format_html( '<span style="background: yellow;">{}</span>', formats.localize(self.due_date)) else: return self.due_date
def l_execution_date(self, inst): if not inst.execution_date: return u'' if inst.status in m.Order.Status.BEFORE_SEND: if inst.execution_today(): return u'<span class="warning" title="Zamówienie powinno zostać \ wysłane dzisiaj.">%s</span>' % formats.localize(inst.execution_date) elif inst.execution_passed(): return u'<span class="fail" title="Przewidywany termin realizacji \ minął.">%s</span>' % formats.localize(inst.execution_date) return formats.localize(inst.execution_date)
def show(self): html = "" if self.show_title and self.title is not None: html += '<div class="title">%s</div>' %self.title if self.show_author and self.author is not None: html += '<div class="author">Autor: %s</div>' %self.author if self.show_date and localize( self.publish_date ) is not None: html += '<div class="date">%s</div>' %localize( self.publish_date ) if self.show_description and self.description is not None: html += '<div class="description">%s</div>' %self.description return mark_safe( html )
def changelist_view(self, request, extra_context=None): # First load a mapping between config name and default value if not self.has_change_permission(request, None): raise PermissionDenied default_initial = ((name, default) for name, (default, help_text) in settings.CONFIG.items()) # Then update the mapping with actually values from the backend initial = dict(default_initial, **dict(config._backend.mget(settings.CONFIG.keys()))) form = ConstanceForm(initial=initial) if request.method == 'POST': form = ConstanceForm(request.POST) if form.is_valid(): form.save() # In django 1.5 this can be replaced with self.message_user messages.add_message( request, messages.SUCCESS, _('Live settings updated successfully.'), ) return HttpResponseRedirect('.') context = { 'config': [], 'title': _('Constance config'), 'app_label': 'constance', 'opts': Config._meta, 'form': form, 'media': self.media + form.media, } for name, (default, help_text) in settings.CONFIG.items(): # Help text could be a dict with advanced options if isinstance(help_text, dict): help_text = help_text.get("help_text","") # First try to load the value from the actual backend value = initial.get(name) # Then if the returned value is None, get the default if value is None: value = getattr(config, name) context['config'].append({ 'name': name, 'default': localize(default), 'help_text': _(help_text), 'value': localize(value), 'modified': value != default, 'form_field': form[name], }) context['config'].sort(key=itemgetter('name')) context_instance = RequestContext(request, current_app=self.admin_site.name) return render_to_response('admin/constance/change_list.html', context, context_instance=context_instance)
def _get_verbose_value(self, raw, field_or_method, obj, **kwargs): if hasattr(field_or_method, 'humanized') and field_or_method.humanized: return field_or_method.humanized(raw, obj, **kwargs) elif hasattr(field_or_method, 'choices') and field_or_method.choices: return getattr(obj, 'get_{}_display'.format(field_or_method.attname))() if isinstance(raw, bool): return raw and ugettext('Yes') or ugettext('No') elif isinstance(raw, datetime.datetime): return formats.localize(timezone.template_localtime(raw)) elif isinstance(raw, (datetime.date, datetime.time)): return formats.localize(raw) else: return raw
def cut(value, autoescape=True): def noop(x): return x if not value: return '' if autoescape: esc = conditional_escape else: esc = noop return mark_safe('<span class="count">{0}</span><span class="sum-gross">{1}</span><span class="sum-net">{2}</span>'.format( esc(value[0]), esc(formats.localize(value[1])), esc(formats.localize(value[2])) ))
def format_column(self, item, field_name, value): if value is None: return self.empty_value_display elif isinstance(value, datetime.datetime): return formats.localize(timezone.template_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, six.integer_types + (decimal.Decimal, float)): return formats.number_format(value) elif isinstance(value, (list, tuple)): return ', '.join(force_text(v) for v in value) else: return force_text(value)
def _get_model_field_verbose_value(self, obj, field): humanize_method_name = 'get_%s_humanized' % field.attname if hasattr(getattr(obj, humanize_method_name, None), '__call__'): return getattr(obj, humanize_method_name)() val = self._get_model_field_raw_value(obj, field) if isinstance(val, bool): val = val and _('Yes') or _('No') elif field.choices: val = getattr(obj, 'get_%s_display' % field.attname)() elif isinstance(val, datetime.datetime): return formats.localize(timezone.template_localtime(val)) elif isinstance(val, (datetime.date, datetime.time)): return formats.localize(val) return val
def to_pdf(self, user, response): filename = ugettext('invoice_%(invoice_id)d.pdf') % {'invoice_id': self.invoice_id} response['Content-Disposition'] = 'attachment; filename=%s' % (filename) invoice_template = InvoiceTemplate(response, user) invoice_template.init_doc(ugettext('Invoice #%(invoice_id)d') % {'invoice_id': self.invoice_id}) invoice_template.add_headers(self, self.customer, self.edition_date) invoice_template.add_title(_("INVOICE #%d") % (self.invoice_id)) # proposal row list rows = self.invoice_rows.all() invoice_template.add_rows(rows) # total amount on the right side of footer right_block = invoice_template.get_total_amount(self.amount, rows) invoice_amount = self.amount invoice_amount = invoice_amount.quantize(Decimal(1)) if invoice_amount == invoice_amount.to_integral() else invoice_amount.normalize() left_block = [Paragraph(_("Payment date : %s") % (localize(self.payment_date)), InvoiceTemplate.styleN), Paragraph(_("Penalty begins on : %s") % (localize(self.penalty_date) or ''), InvoiceTemplate.styleN), Paragraph(_("Penalty rate : %s") % (localize(self.penalty_rate) or ''), InvoiceTemplate.styleN), Paragraph(_("Discount conditions : %s") % (self.discount_conditions or ''), InvoiceTemplate.styleN)] if self.footer_note: left_block.append(Spacer(invoice_template.doc.width, 0.1 * inch)) left_block.append(Paragraph(self.footer_note, InvoiceTemplate.styleNSmall)) else: left_block.append(Spacer(invoice_template.doc.width, 0.2 * inch)) if self.owner.get_profile().iban_bban: left_block.append(Paragraph(_("IBAN/BBAN : %s") % (self.owner.get_profile().iban_bban), InvoiceTemplate.styleNSmall)) if self.owner.get_profile().bic: left_block.append(Paragraph(_("BIC/SWIFT : %s") % (self.owner.get_profile().bic), InvoiceTemplate.styleNSmall)) data = [[left_block, '', right_block], ] if self.execution_begin_date and self.execution_end_date: data[0][0].insert(1, Paragraph(_("Execution dates : %(begin_date)s to %(end_date)s") % {'begin_date': localize(self.execution_begin_date), 'end_date' : localize(self.execution_end_date)}, InvoiceTemplate.styleN)) footer_table = Table(data, [4.5 * inch, 0.3 * inch, 2.5 * inch], [1 * inch]) footer_table.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) invoice_template.append_to_story(footer_table) invoice_template.build() return response
def display_for_value(value, boolean=False): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if boolean: return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(value, datetime.datetime): return formats.localize(tz_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, (decimal.Decimal, float)): return formats.number_format(value) else: return smart_unicode(value)
def _invoice_generate_german(invoice, f): _invoice_register_fonts() styles = _invoice_get_stylesheet() pagesize = pagesizes.A4 def on_page(canvas, doc): canvas.saveState() canvas.setFont('OpenSans', 8) canvas.drawRightString(pagesize[0] - 20 * mm, 10 * mm, _("Page %d") % (doc.page, )) for i, line in enumerate(invoice.footer_text.split('\n')[::-1]): canvas.drawCentredString(pagesize[0] / 2, 25 + (3.5 * i) * mm, line.strip()) canvas.restoreState() def on_first_page(canvas, doc): canvas.setCreator('pretix.eu') canvas.setTitle( pgettext('invoice', 'Invoice {num}').format(num=invoice.number)) canvas.saveState() canvas.setFont('OpenSans', 8) canvas.drawRightString(pagesize[0] - 20 * mm, 10 * mm, _("Page %d") % (doc.page, )) for i, line in enumerate(invoice.footer_text.split('\n')[::-1]): canvas.drawCentredString(pagesize[0] / 2, 25 + (3.5 * i) * mm, line.strip()) textobject = canvas.beginText(25 * mm, (297 - 15) * mm) textobject.setFont('OpenSansBd', 8) textobject.textLine(pgettext('invoice', 'Invoice from').upper()) canvas.drawText(textobject) p = Paragraph(invoice.invoice_from.strip().replace('\n', '<br />\n'), style=styles['Normal']) p.wrapOn(canvas, 70 * mm, 50 * mm) p_size = p.wrap(70 * mm, 50 * mm) p.drawOn(canvas, 25 * mm, (297 - 17) * mm - p_size[1]) textobject = canvas.beginText(25 * mm, (297 - 50) * mm) textobject.setFont('OpenSansBd', 8) textobject.textLine(pgettext('invoice', 'Invoice to').upper()) canvas.drawText(textobject) p = Paragraph(invoice.invoice_to.strip().replace('\n', '<br />\n'), style=styles['Normal']) p.wrapOn(canvas, 85 * mm, 50 * mm) p_size = p.wrap(85 * mm, 50 * mm) p.drawOn(canvas, 25 * mm, (297 - 52) * mm - p_size[1]) textobject = canvas.beginText(125 * mm, (297 - 38) * mm) textobject.setFont('OpenSansBd', 8) textobject.textLine(_('Order code').upper()) textobject.moveCursor(0, 5) textobject.setFont('OpenSans', 10) textobject.textLine(invoice.order.full_code) canvas.drawText(textobject) textobject = canvas.beginText(125 * mm, (297 - 50) * mm) textobject.setFont('OpenSansBd', 8) if invoice.is_cancellation: textobject.textLine( pgettext('invoice', 'Cancellation number').upper()) textobject.moveCursor(0, 5) textobject.setFont('OpenSans', 10) textobject.textLine(invoice.number) textobject.moveCursor(0, 5) textobject.setFont('OpenSansBd', 8) textobject.textLine( pgettext('invoice', 'Original invoice').upper()) textobject.moveCursor(0, 5) textobject.setFont('OpenSans', 10) textobject.textLine(invoice.refers.number) else: textobject.textLine(pgettext('invoice', 'Invoice number').upper()) textobject.moveCursor(0, 5) textobject.setFont('OpenSans', 10) textobject.textLine(invoice.number) textobject.moveCursor(0, 5) if invoice.is_cancellation: textobject.setFont('OpenSansBd', 8) textobject.textLine( pgettext('invoice', 'Cancellation date').upper()) textobject.moveCursor(0, 5) textobject.setFont('OpenSans', 10) textobject.textLine(date_format(invoice.date, "DATE_FORMAT")) textobject.moveCursor(0, 5) textobject.setFont('OpenSansBd', 8) textobject.textLine( pgettext('invoice', 'Original invoice date').upper()) textobject.moveCursor(0, 5) textobject.setFont('OpenSans', 10) textobject.textLine(date_format(invoice.refers.date, "DATE_FORMAT")) textobject.moveCursor(0, 5) else: textobject.setFont('OpenSansBd', 8) textobject.textLine(pgettext('invoice', 'Invoice date').upper()) textobject.moveCursor(0, 5) textobject.setFont('OpenSans', 10) textobject.textLine(date_format(invoice.date, "DATE_FORMAT")) textobject.moveCursor(0, 5) canvas.drawText(textobject) if invoice.event.settings.invoice_logo_image: logo_file = invoice.event.settings.get('invoice_logo_image', binary_file=True) canvas.drawImage(ImageReader(logo_file), 95 * mm, (297 - 38) * mm, width=25 * mm, height=25 * mm, preserveAspectRatio=True, anchor='n', mask='auto') if invoice.event.settings.show_date_to: p_str = (str(invoice.event.name) + '\n' + _('{from_date}\nuntil {to_date}').format( from_date=invoice.event.get_date_from_display(), to_date=invoice.event.get_date_to_display())) else: p_str = (str(invoice.event.name) + '\n' + invoice.event.get_date_from_display()) p = Paragraph(p_str.strip().replace('\n', '<br />\n'), style=styles['Normal']) p.wrapOn(canvas, 65 * mm, 50 * mm) p_size = p.wrap(65 * mm, 50 * mm) p.drawOn(canvas, 125 * mm, (297 - 17) * mm - p_size[1]) textobject = canvas.beginText(125 * mm, (297 - 15) * mm) textobject.setFont('OpenSansBd', 8) textobject.textLine(_('Event').upper()) canvas.drawText(textobject) canvas.restoreState() doc = BaseDocTemplate(f.name, pagesize=pagesizes.A4, leftMargin=25 * mm, rightMargin=20 * mm, topMargin=20 * mm, bottomMargin=15 * mm) footer_length = 3.5 * len(invoice.footer_text.split('\n')) * mm frames_p1 = [ Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height - 75 * mm, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=footer_length, id='normal') ] frames = [ Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=footer_length, id='normal') ] doc.addPageTemplates([ PageTemplate(id='FirstPage', frames=frames_p1, onPage=on_first_page, pagesize=pagesize), PageTemplate(id='OtherPages', frames=frames, onPage=on_page, pagesize=pagesize) ]) story = [ NextPageTemplate('FirstPage'), Paragraph( pgettext('invoice', 'Invoice') if not invoice.is_cancellation else pgettext('invoice', 'Cancellation'), styles['Heading1']), Spacer(1, 5 * mm), NextPageTemplate('OtherPages'), ] if invoice.introductory_text: story.append(Paragraph(invoice.introductory_text, styles['Normal'])) story.append(Spacer(1, 10 * mm)) taxvalue_map = defaultdict(Decimal) grossvalue_map = defaultdict(Decimal) tstyledata = [ ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('FONTNAME', (0, 0), (-1, 0), 'OpenSansBd'), ('FONTNAME', (0, -1), (-1, -1), 'OpenSansBd'), ('LEFTPADDING', (0, 0), (0, -1), 0), ('RIGHTPADDING', (-1, 0), (-1, -1), 0), ] tdata = [( pgettext('invoice', 'Description'), pgettext('invoice', 'Tax rate'), pgettext('invoice', 'Net'), pgettext('invoice', 'Gross'), )] total = Decimal('0.00') for line in invoice.lines.all(): tdata.append(( Paragraph(line.description, styles['Normal']), localize(line.tax_rate) + " %", localize(line.net_value) + " " + invoice.event.currency, localize(line.gross_value) + " " + invoice.event.currency, )) taxvalue_map[line.tax_rate] += line.tax_value grossvalue_map[line.tax_rate] += line.gross_value total += line.gross_value tdata.append([ pgettext('invoice', 'Invoice total'), '', '', localize(total) + " " + invoice.event.currency ]) colwidths = [a * doc.width for a in (.55, .15, .15, .15)] table = Table(tdata, colWidths=colwidths, repeatRows=1) table.setStyle(TableStyle(tstyledata)) story.append(table) story.append(Spacer(1, 15 * mm)) if invoice.payment_provider_text: story.append(Paragraph(invoice.payment_provider_text, styles['Normal'])) if invoice.additional_text: story.append(Paragraph(invoice.additional_text, styles['Normal'])) story.append(Spacer(1, 15 * mm)) tstyledata = [ ('SPAN', (1, 0), (-1, 0)), ('ALIGN', (2, 1), (-1, -1), 'RIGHT'), ('LEFTPADDING', (0, 0), (0, -1), 0), ('RIGHTPADDING', (-1, 0), (-1, -1), 0), ('FONTSIZE', (0, 0), (-1, -1), 8), ] tdata = [('', pgettext('invoice', 'Included taxes'), '', '', ''), ('', pgettext('invoice', 'Tax rate'), pgettext('invoice', 'Net value'), pgettext('invoice', 'Gross value'), pgettext('invoice', 'Tax'))] for rate, gross in grossvalue_map.items(): if line.tax_rate == 0: continue tax = taxvalue_map[rate] tdata.append(( '', localize(rate) + " %", localize((gross - tax)) + " " + invoice.event.currency, localize(gross) + " " + invoice.event.currency, localize(tax) + " " + invoice.event.currency, )) if len(tdata) > 2: colwidths = [a * doc.width for a in (.45, .10, .15, .15, .15)] table = Table(tdata, colWidths=colwidths, repeatRows=2) table.setStyle(TableStyle(tstyledata)) story.append(table) doc.build(story) return doc
def __str__(self): return "[%s] (%s) %s --> %s: %s" % (localize( self.when), self.door_account, self.oude_waarde, self.nieuwe_waarde, self.notitie)
def get_date(self, obj): return localize(obj.created)
def process_form_cell(request, cell): if isinstance(cell, str) and cell.startswith(cr_settings['PROTECTED_MEDIA_URL']): return utils.get_protected_media_link(request, cell, render_link=True) if utils.uri_validator(str(cell)): return mark_safe("<a href='{0}'>{1}</a>".format(cell, cell)) return localize(cell)
def print(self, currency): return '{} + {}% = {}'.format( money_filter(self.net, currency), localize(self.rate), money_filter(self.gross, currency) )
def _display_order_changed(event: Event, logentry: LogEntry): data = json.loads(logentry.data) text = _('The order has been changed:') if logentry.action_type == 'pretix.event.order.changed.item': old_item = str(event.items.get(pk=data['old_item'])) if data['old_variation']: old_item += ' - ' + str( ItemVariation.objects.get(item__event=event, pk=data['old_variation'])) new_item = str(event.items.get(pk=data['new_item'])) if data['new_variation']: new_item += ' - ' + str( ItemVariation.objects.get(item__event=event, pk=data['new_variation'])) return text + ' ' + _( 'Position #{posid}: {old_item} ({old_price} {currency}) changed ' 'to {new_item} ({new_price} {currency}).').format( posid=data.get('positionid', '?'), old_item=old_item, new_item=new_item, old_price=formats.localize(Decimal(data['old_price'])), new_price=formats.localize(Decimal(data['new_price'])), currency=event.currency) elif logentry.action_type == 'pretix.event.order.changed.subevent': old_se = str(event.subevents.get(pk=data['old_subevent'])) new_se = str(event.subevents.get(pk=data['new_subevent'])) return text + ' ' + _( 'Position #{posid}: Event date "{old_event}" ({old_price} {currency}) changed ' 'to "{new_event}" ({new_price} {currency}).').format( posid=data.get('positionid', '?'), old_event=old_se, new_event=new_se, old_price=formats.localize(Decimal(data['old_price'])), new_price=formats.localize(Decimal(data['new_price'])), currency=event.currency) elif logentry.action_type == 'pretix.event.order.changed.price': return text + ' ' + _( 'Price of position #{posid} changed from {old_price} {currency} ' 'to {new_price} {currency}.').format( posid=data.get('positionid', '?'), old_price=formats.localize(Decimal(data['old_price'])), new_price=formats.localize(Decimal(data['new_price'])), currency=event.currency) elif logentry.action_type == 'pretix.event.order.changed.cancel': old_item = str(event.items.get(pk=data['old_item'])) if data['old_variation']: old_item += ' - ' + str( ItemVariation.objects.get(pk=data['old_variation'])) return text + ' ' + _( 'Position #{posid} ({old_item}, {old_price} {currency}) removed.' ).format(posid=data.get('positionid', '?'), old_item=old_item, old_price=formats.localize(Decimal(data['old_price'])), currency=event.currency) elif logentry.action_type == 'pretix.event.order.changed.add': item = str(event.items.get(pk=data['item'])) if data['variation']: item += ' - ' + str( ItemVariation.objects.get(item__event=event, pk=data['variation'])) if data['addon_to']: addon_to = OrderPosition.objects.get(order__event=event, pk=data['addon_to']) return text + ' ' + _( 'Position #{posid} created: {item} ({price} {currency}) as an add-on to ' 'position #{addon_to}.').format( posid=data.get('positionid', '?'), item=item, addon_to=addon_to.positionid, price=formats.localize(Decimal(data['price'])), currency=event.currency) else: return text + ' ' + _( 'Position #{posid} created: {item} ({price} {currency}).' ).format(posid=data.get('positionid', '?'), item=item, price=formats.localize(Decimal(data['price'])), currency=event.currency) elif logentry.action_type == 'pretix.event.order.changed.split': old_item = str(event.items.get(pk=data['old_item'])) if data['old_variation']: old_item += ' - ' + str( ItemVariation.objects.get(pk=data['old_variation'])) return text + ' ' + _( 'Position #{posid} ({old_item}, {old_price} {currency}) split into new order: {order}' ).format(old_item=old_item, posid=data.get('positionid', '?'), order=data['new_order'], old_price=formats.localize(Decimal(data['old_price'])), currency=event.currency) elif logentry.action_type == 'pretix.event.order.changed.split_from': return _('This order has been created by splitting the order {order}' ).format(order=data['original_order'], )
def get(self, request, *args, **kwargs): wb = Workbook() ws = wb.active queryset = Detalle_venta.objects.all().order_by('detalle_venta') marca_id = self.request.GET.get('marca_id') fecha_init = self.request.GET.get('fecha_init') fecha_end = self.request.GET.get('fecha_end') marca_nom = Marca.objects.get(marca_id_marca=marca_id) if fecha_init != None and fecha_init != "": if fecha_end != None and fecha_end != "": queryset = queryset.filter( detalle_venta__venta_e_fecha_pedido__range=[ fecha_init, fecha_end ]) if marca_id != None and marca_id != "": queryset = queryset.filter( detalle_producto_id__producto_marca=marca_id) ws['A1'] = 'TOTAL DE PORDUCTOS EXPO POR MARCAS DE {} AL {} "{}" '.format( localize(datetime.strptime(fecha_init, '%Y-%m-%d').date()), localize(datetime.strptime(fecha_end, '%Y-%m-%d').date()), marca_nom.marca_nombre) st = ws['A1'] st.font = Font(size=14, b=True, color="004ee0") st.alignment = Alignment(horizontal='center') ws.merge_cells('A1:I1') ws.sheet_properties.tabColor = "1072BA" ws['A2'] = 'N° Vent' ws['B2'] = 'Producto' ws['C2'] = 'Descripción' ws['D2'] = 'Cantidad' ws['E2'] = 'Precio' ws['F2'] = 'Subtotal' cont = 3 for item in queryset: ws.cell(row=cont, column=1).value = str(item.detalle_venta) ws.cell(row=cont, column=2).value = str(item.detalle_producto_id) ws.cell( row=cont, column=3).value = item.detalle_producto_id.producto_descripcion ws.cell(row=cont, column=4).value = item.detalle_cantidad ws.cell(row=cont, column=5).value = item.detalle_precio ws.cell(row=cont, column=6).value = item.subtotal() ws.cell(row=cont, column=6).number_format = '#,##0' cont += 1 ws["E" + str(cont)] = "TOTAL" ws["F" + str(cont)] = "=SUM(F3:F" + str(cont - 1) + ")" ws["F" + str(cont)].number_format = '#,##0' dims = {} for row in ws.rows: for cell in row: if cell.value: if cell.row != 1: dims[cell.column] = max( (dims.get(cell.column, 0), len(str(cell.value)))) for col, value in dims.items(): ws.column_dimensions[get_column_letter(col)].width = value + 1 nombre_archivo = 'VENTAS_PRODUCTOS_EXPO_MARCAS.xls' response = HttpResponse(content_type="application/ms-excel") content = "attachment; filename = {0}".format(nombre_archivo) response['Content-Disposition'] = content wb.save(response) return response
def _get_text_content(self, op: OrderPosition, order: Order, o: dict): ev = op.subevent or order.event if o['content'] == 'other': return o['text'].replace("\n", "<br/>\n") elif o['content'].startswith('meta:'): return ev.meta_data.get(o['content'][5:]) or '' elif o['content'] == 'order': return order.code elif o['content'] == 'item': return str(op.item) elif o['content'] == 'item_description': return str(op.item.description) elif o['content'] == 'organizer': return str(order.event.organizer.name) elif o['content'] == 'organizer_info_text': return str(order.event.settings.organizer_info_text) elif o['content'] == 'secret': return op.secret elif o['content'] == 'variation': return str(op.variation) if op.variation else '' elif o['content'] == 'itemvar': return '{} - {}'.format( op.item, op.variation) if op.variation else str(op.item) elif o['content'] == 'price': return '{} {}'.format(order.event.currency, localize(op.price)) elif o['content'] == 'attendee_name': return op.attendee_name or (op.addon_to.attendee_name if op.addon_to else '') elif o['content'] == 'event_name': return str(ev.name) elif o['content'] == 'event_location': return str(ev.location).replace("\n", "<br/>\n") elif o['content'] == 'event_date': return ev.get_date_from_display(show_times=False) elif o['content'] == 'event_date_range': return ev.get_date_range_display() elif o['content'] == 'event_begin': return ev.get_date_from_display(show_times=True) elif o['content'] == 'event_begin_time': return ev.get_time_from_display() elif o['content'] == 'event_admission': if ev.date_admission: tz = timezone(order.event.settings.timezone) return date_format(ev.date_admission.astimezone(tz), "SHORT_DATETIME_FORMAT") elif o['content'] == 'event_admission_time': if ev.date_admission: tz = timezone(order.event.settings.timezone) return date_format(ev.date_admission.astimezone(tz), "TIME_FORMAT") elif o['content'] == 'invoice_name': try: return order.invoice_address.name except: return "" elif o['content'] == 'invoice_company': try: return order.invoice_address.company except: return "" elif o['content'] == 'addons': return "<br/>".join([ '{} - {}'.format(p.item, p.variation) if p.variation else str(p.item) for p in op.addons.select_related('item', 'variation') ]) return ''
def get_story(self, doc, form_data): from reportlab.platypus import Paragraph, Spacer, TableStyle, Table from reportlab.lib.units import mm headlinestyle = self.get_style() headlinestyle.fontSize = 15 headlinestyle.fontName = 'OpenSansBd' tz = pytz.timezone(self.event.settings.timezone) tax_rates = set(a for a in OrderFee.objects.filter( order__event=self.event).values_list( 'tax_rate', flat=True).distinct().order_by()) tax_rates |= set(a for a in OrderPosition.objects.filter( order__event=self.event).filter( order__status__in=self.form_data['status']).values_list( 'tax_rate', flat=True).distinct().order_by()) tax_rates = sorted(tax_rates) # Cols: Order ID | Order date | Status | Payment Date | Total | {gross tax} for t in taxes colwidths = [a * doc.width for a in [0.12, 0.1, 0.10, 0.12, 0.08]] if tax_rates: colwidths += [0.48 / (len(tax_rates) * 2) * doc.width ] * (len(tax_rates) * 2) tstyledata = [ # Alignment ('ALIGN', (0, 0), (3, 0), 'LEFT'), # Headlines ('ALIGN', (4, 0), (-1, 0), 'CENTER'), # Headlines ('ALIGN', (4, 1), (-1, -1), 'RIGHT'), # Money ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # Fonts ('FONTNAME', (0, 0), (-1, 0), 'OpenSansBd'), # Headlines ('FONTNAME', (0, -1), (-1, -1), 'OpenSansBd'), # Sums ] for i, rate in enumerate(tax_rates): tstyledata.append(('SPAN', (5 + 2 * i, 0), (6 + 2 * i, 0))) story = [ Paragraph( _('Orders by tax rate ({currency})').format( currency=self.event.currency), headlinestyle), Spacer(1, 5 * mm) ] tdata = [ [ _('Order code'), _('Order date'), _('Status'), _('Payment date'), _('Order total'), ] + sum(([localize(t) + ' %', ''] for t in tax_rates), []), ['', '', '', '', ''] + sum( ([_('Gross'), _('Tax')] for t in tax_rates), []), ] op_date = OrderPayment.objects.filter( order=OuterRef('order'), state__in=(OrderPayment.PAYMENT_STATE_CONFIRMED, OrderPayment.PAYMENT_STATE_REFUNDED), payment_date__isnull=False).values('order').annotate( m=Max('payment_date')).values('m').order_by() qs = OrderPosition.objects.filter( order__status__in=self.form_data['status'], order__event=self.event, ).annotate(payment_date=Subquery( op_date, output_field=models.DateTimeField())).values( 'order__code', 'order__datetime', 'payment_date', 'order__total', 'tax_rate', 'order__status', 'order__id').annotate( prices=Sum('price'), tax_values=Sum('tax_value')).order_by( 'order__datetime' if self.form_data['sort'] == 'datetime' else 'payment_date', 'order__datetime', 'order__code') fee_sum_cache = { (o['order__id'], o['tax_rate']): o for o in OrderFee.objects.values('tax_rate', 'order__id').order_by( ).annotate(taxsum=Sum('tax_value'), grosssum=Sum('value')) } last_order_code = None tax_sums = defaultdict(Decimal) price_sums = defaultdict(Decimal) status_labels = dict(Order.STATUS_CHOICE) for op in qs: if op['order__code'] != last_order_code: tdata.append([ op['order__code'], date_format(op['order__datetime'].astimezone(tz), "SHORT_DATE_FORMAT"), status_labels[op['order__status']], date_format(op['payment_date'], "SHORT_DATE_FORMAT") if op['payment_date'] else '', op['order__total'] ] + sum((['', ''] for t in tax_rates), []), ) last_order_code = op['order__code'] for i, rate in enumerate(tax_rates): odata = fee_sum_cache.get((op['order__id'], rate)) if odata: tdata[-1][5 + 2 * i] = odata['grosssum'] or Decimal('0.00') tdata[-1][6 + 2 * i] = odata['taxsum'] or Decimal('0.00') tax_sums[rate] += odata['taxsum'] or Decimal('0.00') price_sums[rate] += odata['grosssum'] or Decimal( '0.00') i = tax_rates.index(op['tax_rate']) tdata[-1][5 + 2 * i] = (tdata[-1][5 + 2 * i] or Decimal('0.00')) + op['prices'] tdata[-1][6 + 2 * i] = (tdata[-1][6 + 2 * i] or Decimal('0.00')) + op['tax_values'] tax_sums[op['tax_rate']] += op['tax_values'] price_sums[op['tax_rate']] += op['prices'] tdata.append([_('Total'), '', '', '', ''] + sum(([ price_sums.get(t) or Decimal('0.00'), tax_sums.get(t) or Decimal('0.00') ] for t in tax_rates), []), ) tdata = [[ localize(round_decimal(c, self.event.currency)) if isinstance( c, (Decimal, int, float)) else c for c in row ] for row in tdata] table = Table(tdata, colWidths=colwidths, repeatRows=2) table.setStyle(TableStyle(tstyledata)) story.append(table) return story
def format(self, value): if isinstance(value, datetime.datetime) or isinstance(value, datetime.date): return localize(value) return value
def changes_display_dict(self): """ :return: The changes recorded in this log entry intended for display to users as a dictionary object. """ # Get the model and model_fields from auditlog.registry import auditlog model = self.content_type.model_class() model_fields = auditlog.get_model_fields(model._meta.model) changes_display_dict = {} # grab the changes_dict and iterate through for field_name, values in iteritems(self.changes_dict): # try to get the field attribute on the model try: field = model._meta.get_field(field_name) except FieldDoesNotExist: changes_display_dict[field_name] = values continue values_display = [] # handle choices fields and Postgres ArrayField to get human readable version choices_dict = None if hasattr(field, 'choices') and len(field.choices) > 0: choices_dict = dict(field.choices) if hasattr(field, 'base_field') and getattr( field.base_field, 'choices', False): choices_dict = dict(field.base_field.choices) if choices_dict: for value in values: try: value = ast.literal_eval(value) if type(value) is [].__class__: values_display.append(', '.join([ choices_dict.get(val, 'None') for val in value ])) else: values_display.append( choices_dict.get(value, 'None')) except ValueError: values_display.append(choices_dict.get(value, 'None')) except: values_display.append(choices_dict.get(value, 'None')) else: try: field_type = field.get_internal_type() except AttributeError: # if the field is a relationship it has no internal type and exclude it continue for value in values: # handle case where field is a datetime, date, or time type if field_type in [ "DateTimeField", "DateField", "TimeField" ]: try: value = parser.parse(value) if field_type == "DateField": value = value.date() elif field_type == "TimeField": value = value.time() elif field_type == "DateTimeField": value = value.replace(tzinfo=timezone.utc) value = value.astimezone( gettz(settings.TIME_ZONE)) value = formats.localize(value) except ValueError: pass # check if length is longer than 140 and truncate with ellipsis if len(value) > 140: value = "{}...".format(value[:140]) values_display.append(value) verbose_name = model_fields['mapping_fields'].get( field.name, getattr(field, 'verbose_name', field.name)) changes_display_dict[verbose_name] = values_display return changes_display_dict
def fmt(val): try: return vat_moss.exchange_rates.format(val, self.invoice.foreign_currency_display) except ValueError: return localize(val) + ' ' + self.invoice.foreign_currency_display
def introduce_new_people(): org = Organization.object.get() if not AccessToken.objects.filter(integration=0).exists() or not org.ask_colleague_welcome_message: return s = Slack() translation.activate(org.language) new_hires = get_user_model().objects.filter( is_introduced_to_colleagues=False, role=0, start_day__gt=datetime.now().date() ) if new_hires.exists(): blocks = [] if new_hires.count() > 1: text = _("We got some new hires coming in soon! Make sure to leave a welcome message for them!") else: text = _( "We have a new hire coming in soon! Make sure to leave a message for ") + new_hires.first().first_name + "!" blocks.append({ "type": "section", "text": { "type": "mrkdwn", "text": text } }) for new_hire in new_hires: message = "*" + new_hire.full_name() + "*" if new_hire.message != "": message += "\n_" + new_hire.message + "_" block = { "type": "section", "text": { "type": "mrkdwn", "text": message } } if new_hire.profile_image: block["accessory"] = { "type": "image", "image_url": new_hire.profile_image.get_url(), "alt_text": "profile image" } blocks.append(block) footer_extra = "" if new_hire.position is not None and new_hire.position != "": footer_extra = _(" and is our new ") + new_hire.position context = new_hire.first_name + _(" starts on ") + localize(new_hire.start_day) + footer_extra + "." blocks.append({ "type": "context", "elements": [{ "type": "plain_text", "text": context }] }) blocks.append({ "type": "actions", "elements": [ { "type": "button", "text": { "type": "plain_text", "text": _("Welcome this new hire!") }, "value": "dialog:welcome:" + str(new_hire.id) } ] }) new_hire.is_introduced_to_colleagues = True new_hire.save() s.send_message(channel="#general", blocks=blocks)
def __unicode__(self): return u"{title} - {facility} ({start} - {end})".format( title=self.task.name, facility=self.facility.name, start=localize(self.starting_time), end=localize(self.ending_time))
def render_revision_form(self, request, obj, version, context, revert=False, recover=False): """Renders the object revision form.""" model = self.model opts = model._meta object_id = obj.pk # Generate the model form. ModelForm = self.get_form(request, obj) formsets = [] if request.method == "POST": # This section is copied directly from the model admin change view # method. Maybe one day there will be a hook for doing this better. form = ModelForm(request.POST, request.FILES, instance=obj, initial=self.get_revision_form_data( request, obj, version)) if form.is_valid(): form_validated = True new_object = self.save_form(request, form, change=True) # HACK: If the value of a file field is None, remove the file from the model. for field in new_object._meta.fields: if isinstance( field, models.FileField ) and field.name in form.cleaned_data and form.cleaned_data[ field.name] is None: setattr(new_object, field.name, None) else: form_validated = False new_object = obj prefixes = {} for FormSet, inline in zip(self.get_formsets(request, new_object), self.get_inline_instances(request)): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(request.POST, request.FILES, instance=new_object, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(inline, FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, change=True) form.save_m2m() for formset in formsets: # HACK: If the value of a file field is None, remove the file from the model. related_objects = formset.save(commit=False) for related_obj, related_form in zip( related_objects, formset.saved_forms): for field in related_obj._meta.fields: if isinstance( field, models.FileField ) and field.name in related_form.cleaned_data and related_form.cleaned_data[ field.name] is None: setattr(related_obj, field.name, None) related_obj.save() formset.save_m2m() change_message = _( "Reverted to previous version, saved on %(datetime)s") % { "datetime": localize(version.revision.date_created) } self.log_change(request, new_object, change_message) self.message_user( request, _('The %(model)s "%(name)s" was reverted successfully. You may edit it again below.' ) % { "model": force_text(opts.verbose_name), "name": force_text(obj) }) # Redirect to the model change form. if revert: return HttpResponseRedirect("../../") elif recover: return HttpResponseRedirect("../../%s/" % quote(object_id)) else: assert False else: # This is a mutated version of the code in the standard model admin # change_view. Once again, a hook for this kind of functionality # would be nice. Unfortunately, it results in doubling the number # of queries required to construct the formets. form = ModelForm(instance=obj, initial=self.get_revision_form_data( request, obj, version)) prefixes = {} for FormSet, inline in zip(self.get_formsets(request, obj), self.get_inline_instances(request)): # This code is standard for creating the formset. prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(instance=obj, prefix=prefix, queryset=inline.queryset(request)) self._hack_inline_formset_initial(inline, FormSet, formset, obj, version, revert, recover) # Add this hacked formset to the form. formsets.append(formset) # Generate admin form helper. adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields, self.get_readonly_fields(request, obj), model_admin=self) media = self.media + adminForm.media # Generate formset helpers. inline_admin_formsets = [] for inline, formset in zip(self.get_inline_instances(request), formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) prepopulated = inline.get_prepopulated_fields(request, obj) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, prepopulated, readonly, model_admin=self) inline_admin_formsets.append(inline_admin_formset) media = media + inline_admin_formset.media # Generate the context. context.update({ "adminform": adminForm, "object_id": object_id, "original": obj, "is_popup": False, "media": mark_safe(media), "inline_admin_formsets": inline_admin_formsets, "errors": helpers.AdminErrorList(form, formsets), "app_label": opts.app_label, "add": False, "change": True, "revert": revert, "recover": recover, "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), "has_file_field": True, "has_absolute_url": False, "form_url": mark_safe(request.path), "opts": opts, "content_type_id": ContentType.objects.get_for_model(self.model).id, "save_as": False, "save_on_top": self.save_on_top, "changelist_url": reverse("%s:%s_%s_changelist" % (self.admin_site.name, opts.app_label, opts.module_name)), "change_url": reverse("%s:%s_%s_change" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(obj.pk), )), "history_url": reverse("%s:%s_%s_history" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(obj.pk), )), "recoverlist_url": reverse("%s:%s_%s_recoverlist" % (self.admin_site.name, opts.app_label, opts.module_name)) }) # Render the form. if revert: form_template = self.revision_form_template or self._get_template_list( "revision_form.html") elif recover: form_template = self.recover_form_template or self._get_template_list( "recover_form.html") else: assert False return render_to_response(form_template, context, template.RequestContext(request))
def _get_story(self, doc): has_taxes = any(il.tax_value for il in self.invoice.lines.all()) story = [ NextPageTemplate('FirstPage'), Paragraph((pgettext('invoice', 'Tax Invoice') if str( self.invoice.invoice_from_country) == 'AU' else pgettext( 'invoice', 'Invoice')) if not self.invoice.is_cancellation else pgettext('invoice', 'Cancellation'), self.stylesheet['Heading1']), Spacer(1, 5 * mm), NextPageTemplate('OtherPages'), ] story += self._get_intro() taxvalue_map = defaultdict(Decimal) grossvalue_map = defaultdict(Decimal) tstyledata = [ ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('FONTNAME', (0, 0), (-1, 0), self.font_bold), ('FONTNAME', (0, -1), (-1, -1), self.font_bold), ('LEFTPADDING', (0, 0), (0, -1), 0), ('RIGHTPADDING', (-1, 0), (-1, -1), 0), ] if has_taxes: tdata = [( pgettext('invoice', 'Description'), pgettext('invoice', 'Qty'), pgettext('invoice', 'Tax rate'), pgettext('invoice', 'Net'), pgettext('invoice', 'Gross'), )] else: tdata = [( pgettext('invoice', 'Description'), pgettext('invoice', 'Qty'), pgettext('invoice', 'Amount'), )] total = Decimal('0.00') for line in self.invoice.lines.all(): if has_taxes: tdata.append(( Paragraph(line.description, self.stylesheet['Normal']), "1", localize(line.tax_rate) + " %", money_filter(line.net_value, self.invoice.event.currency), money_filter(line.gross_value, self.invoice.event.currency), )) else: tdata.append(( Paragraph(line.description, self.stylesheet['Normal']), "1", money_filter(line.gross_value, self.invoice.event.currency), )) taxvalue_map[line.tax_rate, line.tax_name] += line.tax_value grossvalue_map[line.tax_rate, line.tax_name] += line.gross_value total += line.gross_value if has_taxes: tdata.append([ pgettext('invoice', 'Invoice total'), '', '', '', money_filter(total, self.invoice.event.currency) ]) colwidths = [a * doc.width for a in (.50, .05, .15, .15, .15)] else: tdata.append([ pgettext('invoice', 'Invoice total'), '', money_filter(total, self.invoice.event.currency) ]) colwidths = [a * doc.width for a in (.65, .05, .30)] if self.invoice.event.settings.invoice_show_payments and not self.invoice.is_cancellation and \ self.invoice.order.status == Order.STATUS_PENDING: pending_sum = self.invoice.order.pending_sum if pending_sum != total: tdata.append([pgettext('invoice', 'Received payments')] + (['', '', ''] if has_taxes else ['']) + [ money_filter(pending_sum - total, self.invoice.event.currency) ]) tdata.append( [pgettext('invoice', 'Outstanding payments')] + (['', '', ''] if has_taxes else ['']) + [money_filter(pending_sum, self.invoice.event.currency)]) tstyledata += [ ('FONTNAME', (0, len(tdata) - 3), (-1, len(tdata) - 3), self.font_bold), ] table = Table(tdata, colWidths=colwidths, repeatRows=1) table.setStyle(TableStyle(tstyledata)) story.append(table) story.append(Spacer(1, 15 * mm)) if self.invoice.payment_provider_text: story.append( Paragraph(self.invoice.payment_provider_text, self.stylesheet['Normal'])) if self.invoice.additional_text: story.append( Paragraph(self.invoice.additional_text, self.stylesheet['Normal'])) story.append(Spacer(1, 15 * mm)) tstyledata = [ ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ('LEFTPADDING', (0, 0), (0, -1), 0), ('RIGHTPADDING', (-1, 0), (-1, -1), 0), ('FONTSIZE', (0, 0), (-1, -1), 8), ('FONTNAME', (0, 0), (-1, -1), self.font_regular), ] thead = [ pgettext('invoice', 'Tax rate'), pgettext('invoice', 'Net value'), pgettext('invoice', 'Gross value'), pgettext('invoice', 'Tax'), '' ] tdata = [thead] for idx, gross in grossvalue_map.items(): rate, name = idx if rate == 0: continue tax = taxvalue_map[idx] tdata.append([ localize(rate) + " % " + name, money_filter(gross - tax, self.invoice.event.currency), money_filter(gross, self.invoice.event.currency), money_filter(tax, self.invoice.event.currency), '' ]) def fmt(val): try: return vat_moss.exchange_rates.format( val, self.invoice.foreign_currency_display) except ValueError: return localize( val) + ' ' + self.invoice.foreign_currency_display if len(tdata) > 1 and has_taxes: colwidths = [a * doc.width for a in (.25, .15, .15, .15, .3)] table = Table(tdata, colWidths=colwidths, repeatRows=2, hAlign=TA_LEFT) table.setStyle(TableStyle(tstyledata)) story.append(Spacer(5 * mm, 5 * mm)) story.append( KeepTogether([ Paragraph(pgettext('invoice', 'Included taxes'), self.stylesheet['FineprintHeading']), table ])) if self.invoice.foreign_currency_display and self.invoice.foreign_currency_rate: tdata = [thead] for idx, gross in grossvalue_map.items(): rate, name = idx if rate == 0: continue tax = taxvalue_map[idx] gross = round_decimal(gross * self.invoice.foreign_currency_rate) tax = round_decimal(tax * self.invoice.foreign_currency_rate) net = gross - tax tdata.append([ localize(rate) + " % " + name, fmt(net), fmt(gross), fmt(tax), '' ]) table = Table(tdata, colWidths=colwidths, repeatRows=2, hAlign=TA_LEFT) table.setStyle(TableStyle(tstyledata)) story.append( KeepTogether([ Spacer(1, height=2 * mm), Paragraph( pgettext( 'invoice', 'Using the conversion rate of 1:{rate} as published by the European Central Bank on ' '{date}, this corresponds to:'). format(rate=localize( self.invoice.foreign_currency_rate), date=date_format( self.invoice.foreign_currency_rate_date, "SHORT_DATE_FORMAT")), self.stylesheet['Fineprint']), Spacer(1, height=3 * mm), table ])) elif self.invoice.foreign_currency_display and self.invoice.foreign_currency_rate: story.append(Spacer(1, 5 * mm)) story.append( Paragraph( pgettext( 'invoice', 'Using the conversion rate of 1:{rate} as published by the European Central Bank on ' '{date}, the invoice total corresponds to {total}.'). format(rate=localize(self.invoice.foreign_currency_rate), date=date_format( self.invoice.foreign_currency_rate_date, "SHORT_DATE_FORMAT"), total=fmt(total)), self.stylesheet['Fineprint'])) return story
def render(self, form_data: dict): output = io.StringIO() tz = pytz.timezone(self.event.settings.timezone) writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC, delimiter=",") qs = self.event.orders.all().select_related( 'invoice_address').prefetch_related('invoices') if form_data['paid_only']: qs = qs.filter(status=Order.STATUS_PAID) tax_rates = self._get_all_tax_rates(qs) headers = [ _('Order code'), _('Order total'), _('Status'), _('Email'), _('Order date'), _('Company'), _('Name'), _('Address'), _('ZIP code'), _('City'), _('Country'), _('VAT ID'), _('Payment date'), _('Payment type'), _('Fees'), ] for tr in tax_rates: headers += [ _('Gross at {rate} % tax').format(rate=tr), _('Net at {rate} % tax').format(rate=tr), _('Tax value at {rate} % tax').format(rate=tr), ] headers.append(_('Invoice numbers')) writer.writerow(headers) provider_names = { k: v.verbose_name for k, v in self.event.get_payment_providers().items() } full_fee_sum_cache = { o['order__id']: o['grosssum'] for o in OrderFee.objects.values('tax_rate', 'order__id').order_by( ).annotate(grosssum=Sum('value')) } fee_sum_cache = { (o['order__id'], o['tax_rate']): o for o in OrderFee.objects.values('tax_rate', 'order__id').order_by( ).annotate(taxsum=Sum('tax_value'), grosssum=Sum('value')) } sum_cache = { (o['order__id'], o['tax_rate']): o for o in OrderPosition.objects.values('tax_rate', 'order__id'). order_by().annotate(taxsum=Sum('tax_value'), grosssum=Sum('price')) } for order in qs.order_by('datetime'): row = [ order.code, localize(order.total), order.get_status_display(), order.email, order.datetime.astimezone(tz).strftime('%Y-%m-%d'), ] try: row += [ order.invoice_address.company, order.invoice_address.name, order.invoice_address.street, order.invoice_address.zipcode, order.invoice_address.city, order.invoice_address.country if order.invoice_address.country else order.invoice_address.country_old, order.invoice_address.vat_id, ] except InvoiceAddress.DoesNotExist: row += ['', '', '', '', '', '', ''] row += [ order.payment_date.astimezone(tz).strftime('%Y-%m-%d') if order.payment_date else '', provider_names.get(order.payment_provider, order.payment_provider), localize(full_fee_sum_cache.get(order.id) or Decimal('0.00')) ] for tr in tax_rates: taxrate_values = sum_cache.get((order.id, tr), { 'grosssum': Decimal('0.00'), 'taxsum': Decimal('0.00') }) fee_taxrate_values = fee_sum_cache.get( (order.id, tr), { 'grosssum': Decimal('0.00'), 'taxsum': Decimal('0.00') }) row += [ localize(taxrate_values['grosssum'] + fee_taxrate_values['grosssum']), localize(taxrate_values['grosssum'] - taxrate_values['taxsum'] + fee_taxrate_values['grosssum'] - fee_taxrate_values['taxsum']), localize(taxrate_values['taxsum'] + fee_taxrate_values['taxsum']), ] row.append(', '.join([i.number for i in order.invoices.all()])) writer.writerow(row) return 'orders.csv', 'text/csv', output.getvalue().encode("utf-8")
def base_widgets(sender, subevent=None, **kwargs): prodc = Item.objects.filter( event=sender, active=True, ).filter((Q(available_until__isnull=True) | Q(available_until__gte=now())) & (Q(available_from__isnull=True) | Q(available_from__lte=now()))).count() if subevent: opqs = OrderPosition.objects.filter(subevent=subevent) else: opqs = OrderPosition.objects tickc = opqs.filter( order__event=sender, item__admission=True, order__status__in=(Order.STATUS_PAID, Order.STATUS_PENDING), ).count() paidc = opqs.filter( order__event=sender, item__admission=True, order__status=Order.STATUS_PAID, ).count() if subevent: rev = opqs.filter(order__event=sender, order__status=Order.STATUS_PAID).aggregate( sum=Sum('price'))['sum'] or Decimal('0.00') else: rev = Order.objects.filter( event=sender, status=Order.STATUS_PAID).aggregate( sum=Sum('total'))['sum'] or Decimal('0.00') return [ { 'content': NUM_WIDGET.format(num=tickc, text=_('Attendees (ordered)')), 'display_size': 'small', 'priority': 100, 'url': reverse('control:event.orders', kwargs={ 'event': sender.slug, 'organizer': sender.organizer.slug }) + ('?subevent={}'.format(subevent.pk) if subevent else '') }, { 'content': NUM_WIDGET.format(num=paidc, text=_('Attendees (paid)')), 'display_size': 'small', 'priority': 100, 'url': reverse('control:event.orders.overview', kwargs={ 'event': sender.slug, 'organizer': sender.organizer.slug }) + ('?subevent={}'.format(subevent.pk) if subevent else '') }, { 'content': NUM_WIDGET.format(num=formats.localize( round_decimal(rev, sender.currency)), text=_('Total revenue ({currency})').format( currency=sender.currency)), 'display_size': 'small', 'priority': 100, 'url': reverse('control:event.orders.overview', kwargs={ 'event': sender.slug, 'organizer': sender.organizer.slug }) + ('?subevent={}'.format(subevent.pk) if subevent else '') }, { 'content': NUM_WIDGET.format(num=prodc, text=_('Active products')), 'display_size': 'small', 'priority': 100, 'url': reverse('control:event.items', kwargs={ 'event': sender.slug, 'organizer': sender.organizer.slug }) }, ]
def created_at_localtime_localize(self): return localize(localtime(self.created_at))
def base_widgets(sender, **kwargs): prodc = Item.objects.filter( event=sender, active=True, ).count() tickc = OrderPosition.objects.filter( order__event=sender, item__admission=True, order__status__in=(Order.STATUS_PAID, Order.STATUS_PENDING)).count() paidc = OrderPosition.objects.filter( order__event=sender, item__admission=True, order__status=Order.STATUS_PAID, ).count() rev = Order.objects.filter(event=sender, status=Order.STATUS_PAID).aggregate( sum=Sum('total'))['sum'] or Decimal('0.00') return [ { 'content': NUM_WIDGET.format(num=tickc, text=_('Attendees (ordered)')), 'width': 3, 'priority': 100, 'url': reverse('control:event.orders', kwargs={ 'event': sender.slug, 'organizer': sender.organizer.slug }) }, { 'content': NUM_WIDGET.format(num=paidc, text=_('Attendees (paid)')), 'width': 3, 'priority': 100, 'url': reverse('control:event.orders.overview', kwargs={ 'event': sender.slug, 'organizer': sender.organizer.slug }) }, { 'content': NUM_WIDGET.format(num=formats.localize(rev), text=_('Total revenue ({currency})').format( currency=sender.currency)), 'width': 3, 'priority': 100, 'url': reverse('control:event.orders.overview', kwargs={ 'event': sender.slug, 'organizer': sender.organizer.slug }) }, { 'content': NUM_WIDGET.format(num=prodc, text=_('Active products')), 'width': 3, 'priority': 100, 'url': reverse('control:event.items', kwargs={ 'event': sender.slug, 'organizer': sender.organizer.slug }) }, ]
def get(self, request, *args, **kwargs): wb = Workbook() ws = wb.active queryset = VentaExpo.objects.all() if self.request.user.is_superuser == False: try: supervisor = AsignacionVendedor_a_Supervisor.objects.get( avs_Supervisor=self.request.user) vendedores = supervisor.avs_vendedors.values_list('id') queryset = queryset.filter(venta_e_creado__in=vendedores ).order_by('venta_e_fecha_pedido') except ObjectDoesNotExist: queryset = queryset.none() messages.warning( self.request, 'Es necesario que se le asigne vendedores al usuario "' + str(self.request.user) + '" posteriormente actualice la pagina') venta_e_fecha_pedido_init = self.request.GET.get( 'venta_e_fecha_pedido_init') venta_e_fecha_pedido_end = self.request.GET.get( 'venta_e_fecha_pedido_end') venta_e_cliente = self.request.GET.get('venta_e_cliente') venta_e_status = self.request.GET.get('venta_e_status') venta_e_tipo = self.request.GET.get('venta_e_tipo') venta_e_creado = self.request.GET.get('venta_e_creado') Buscar = self.request.GET.get('Buscar') if venta_e_fecha_pedido_init != None and venta_e_fecha_pedido_init != "": if venta_e_fecha_pedido_end != None and venta_e_fecha_pedido_end != "": queryset = queryset.filter( venta_e_fecha_pedido__range=(venta_e_fecha_pedido_init, venta_e_fecha_pedido_end)) if venta_e_cliente != None and venta_e_cliente != "": queryset = queryset.filter( venta_e_cliente__cli_clave=venta_e_cliente) if venta_e_status != None and venta_e_status != "": queryset = queryset.filter(venta_e_status=venta_e_status) if venta_e_tipo != None and venta_e_tipo != "": queryset = queryset.filter(venta_e_tipo=venta_e_tipo) if Buscar != None and Buscar != "": queryset = queryset.filter(Venta_ID=Buscar) if venta_e_creado != None and venta_e_creado != "": queryset = queryset.filter(venta_e_creado=venta_e_creado) ws['A1'] = 'Ventas Expo' st = ws['A1'] st.font = Font(size=14, b=True, color="004ee0") st.alignment = Alignment(horizontal='center') ws.merge_cells('A1:G1') ws.sheet_properties.tabColor = "1072BA" ws['A2'] = '##' ws['B2'] = 'Fecha' ws['C2'] = 'Actualizado' ws['D2'] = 'Cliente' ws['E2'] = 'Creador' ws['F2'] = 'Tipo' ws['G2'] = 'Total' ws['H2'] = 'Status' cont = 3 for item in queryset: ws.cell(row=cont, column=1).value = item.Venta_ID ws.cell(row=cont, column=2).value = localize(item.venta_e_fecha_pedido) ws.cell(row=cont, column=3).value = localize(item.venta_e_actualizado) ws.cell(row=cont, column=4).value = item.venta_e_cliente.cli_clave ws.cell(row=cont, column=5).value = str(item.venta_e_creado) ws.cell(row=cont, column=6).value = item.get_venta_e_tipo_display() ws.cell(row=cont, column=7).value = item.total_venta() ws.cell(row=cont, column=8).value = item.get_status_display() # ws.cell(row=cont, column=8).fill = PatternFill(bgColor="00ff7f", fill_type = "solid") ws.cell(row=cont, column=7).number_format = '#,##0' cont += 1 ws["F" + str(cont)] = "TOTAL" ws["G" + str(cont)] = "=SUM(G3:G" + str(cont - 1) + ")" ws["G" + str(cont)].number_format = '#,##0' dims = {} for row in ws.rows: for cell in row: if cell.value: if cell.row != 1: dims[cell.column] = max( (dims.get(cell.column, 0), len(str(cell.value)))) for col, value in dims.items(): ws.column_dimensions[get_column_letter(col)].width = value + 1 nombre_archivo = 'VENTAS_EXPO.xls' response = HttpResponse(content_type="application/ms-excel") content = "attachment; filename = {0}".format(nombre_archivo) response['Content-Disposition'] = content wb.save(response) return response
def get_price(self, product): price = product.get_price(self.context['request']) return localize(price)
def action_time_display(self): return u'{0} ({1})'.format(localize(self.action_time), humanize_timesince(self.action_time))
def localize(value): """ Forces a value to be rendered as a localized value, regardless of the value of ``settings.USE_L10N``. """ return force_text(formats.localize(value, use_l10n=True))
def __repr__(self): return '{} + {}% = {}'.format(localize(self.net), localize(self.rate), localize(self.gross))
def default(self, o): # o is the object to serialize -- we can't rename the argument in JSONEncoder if isinstance(o, (date, time, datetime)): return localize(o) return super().default(o)
def get_result_aggregate(self): # print self.list_display result_aggregate = [] result_aggregate_queryset = None result_aggregate_from_normal_queryset = {} result_aggregate_from_annotate_queryset = {} # from django.db import connection # connection.queries = [] qs = self.queryset if self.model_admin.aggregate_fields_from_normal: # print "normal" result_aggregate_from_normal_queryset = self.query_to_normal_aggregate.aggregate( *self.model_admin.aggregate_fields_from_normal) # print "########## result_aggregate_from_normal_queryset ##########" # print result_aggregate_from_normal_queryset if self.model_admin.aggregate_fields_from_annotate: # print "annotate" result_aggregate_from_annotate_queryset = qs.aggregate( *self.model_admin.aggregate_fields_from_annotate) # print "########## result_aggregate_from_annotate_queryset ##########" # print result_aggregate_from_annotate_queryset # print "#######" # print qs.query # print connection.queries result_aggregate_queryset = dict( result_aggregate_from_normal_queryset, **result_aggregate_from_annotate_queryset) # print result_aggregate_queryset if result_aggregate_queryset: for column in self.list_display: result_aggregate_temp = None if column in self.model_admin.map_display_fields_and_aggregate: for aggregate in self.model_admin.map_display_fields_and_aggregate[ column]: # clean_name_field = aggregate[0][:-len(aggregate[0][aggregate[0].rfind("__"):])] pos_value_place_holder = aggregate[2].find("%value") aggregate_string_replace = "<strong>{0}:</strong> {1}" if pos_value_place_holder != -1: aggregate_string_replace = aggregate[2].replace( "%value", "{1}") if isinstance(result_aggregate_queryset[aggregate[0]], float): label_foot = formats.number_format( result_aggregate_queryset[aggregate[0]], 2) else: label_foot = formats.localize( result_aggregate_queryset[aggregate[0]], use_l10n=True) label_foot = aggregate_string_replace.format( aggregate[2], label_foot) result_aggregate_temp = "{0}<br>{1}".format( result_aggregate_temp, label_foot ) if result_aggregate_temp else label_foot # print "@@@@@@@@@@@@@@@@@@@@@@@" if result_aggregate_temp: result_aggregate.append(result_aggregate_temp) else: result_aggregate.append("") # print "################### result_aggregate #####################" # print result_aggregate self.result_aggregate = result_aggregate
def get_date_modified(self, obj): """Displays the last modified date of the given object, typically for use in a change list.""" return localize(obj.date_modified)
def iterate_orders(self, form_data: dict): tz = pytz.timezone(self.event.settings.timezone) p_date = OrderPayment.objects.filter( order=OuterRef('pk'), state__in=(OrderPayment.PAYMENT_STATE_CONFIRMED, OrderPayment.PAYMENT_STATE_REFUNDED), payment_date__isnull=False).values('order').annotate( m=Max('payment_date')).values('m').order_by() qs = self.event.orders.annotate( payment_date=Subquery(p_date, output_field=DateTimeField( ))).select_related('invoice_address').prefetch_related('invoices') if form_data['paid_only']: qs = qs.filter(status=Order.STATUS_PAID) tax_rates = self._get_all_tax_rates(qs) headers = [ _('Order code'), _('Order total'), _('Status'), _('Email'), _('Order date'), _('Company'), _('Name'), ] name_scheme = PERSON_NAME_SCHEMES[self.event.settings.name_scheme] if len(name_scheme['fields']) > 1: for k, label, w in name_scheme['fields']: headers.append(label) headers += [ _('Address'), _('ZIP code'), _('City'), _('Country'), _('VAT ID'), _('Date of last payment'), _('Fees'), _('Order locale') ] for tr in tax_rates: headers += [ _('Gross at {rate} % tax').format(rate=tr), _('Net at {rate} % tax').format(rate=tr), _('Tax value at {rate} % tax').format(rate=tr), ] headers.append(_('Invoice numbers')) yield headers full_fee_sum_cache = { o['order__id']: o['grosssum'] for o in OrderFee.objects.values('tax_rate', 'order__id').order_by( ).annotate(grosssum=Sum('value')) } fee_sum_cache = { (o['order__id'], o['tax_rate']): o for o in OrderFee.objects.values('tax_rate', 'order__id').order_by( ).annotate(taxsum=Sum('tax_value'), grosssum=Sum('value')) } sum_cache = { (o['order__id'], o['tax_rate']): o for o in OrderPosition.objects.values('tax_rate', 'order__id'). order_by().annotate(taxsum=Sum('tax_value'), grosssum=Sum('price')) } for order in qs.order_by('datetime'): row = [ order.code, localize(order.total), order.get_status_display(), order.email, order.datetime.astimezone(tz).strftime('%Y-%m-%d'), ] try: row += [ order.invoice_address.company, order.invoice_address.name, ] if len(name_scheme['fields']) > 1: for k, label, w in name_scheme['fields']: row.append(order.invoice_address.name_parts.get(k, '')) row += [ order.invoice_address.street, order.invoice_address.zipcode, order.invoice_address.city, order.invoice_address.country if order.invoice_address.country else order.invoice_address.country_old, order.invoice_address.vat_id, ] except InvoiceAddress.DoesNotExist: row += [''] * (7 + (len(name_scheme['fields']) if len(name_scheme['fields']) > 1 else 0)) row += [ order.payment_date.astimezone(tz).strftime('%Y-%m-%d') if order.payment_date else '', localize(full_fee_sum_cache.get(order.id) or Decimal('0.00')), order.locale, ] for tr in tax_rates: taxrate_values = sum_cache.get((order.id, tr), { 'grosssum': Decimal('0.00'), 'taxsum': Decimal('0.00') }) fee_taxrate_values = fee_sum_cache.get( (order.id, tr), { 'grosssum': Decimal('0.00'), 'taxsum': Decimal('0.00') }) row += [ localize(taxrate_values['grosssum'] + fee_taxrate_values['grosssum']), localize(taxrate_values['grosssum'] - taxrate_values['taxsum'] + fee_taxrate_values['grosssum'] - fee_taxrate_values['taxsum']), localize(taxrate_values['taxsum'] + fee_taxrate_values['taxsum']), ] row.append(', '.join([i.number for i in order.invoices.all()])) yield row
def unlocalize(value): """ Force a value to be rendered as a non-localized value, regardless of the value of ``settings.USE_L10N``. """ return str(formats.localize(value, use_l10n=False))