Example #1
0
    def to_api(self):
        contexto = {'id': str(self.id),
                    'loja': self.loja.to_dict() if self.loja else None,
                    'descricao': self.descricao,
                    'texto_do_link': self.texto_link,
                    'chamada_promocional': self.texto_promocional,
                    'imagem': self.get_image(),
                    'compartilhamentos': self.total_visto,
                    'curtidas': self.total_curtido,
                    'categoria': [c.to_dict() for c in self.categoria.all()],
                    'expira': self.expira_str,
                    'titulo': self.nome,
                    'tipo': Oferta.TIPOS[self.tipo][1],
                    'inicio': _date(self.inicio, 'd/m/Y'),
                    'fim': _date(self.fim, 'd/m/Y'),
                    'fim_curto': _date(self.fim, 'd/m'),
                    'genero': self.GENEROS[self.genero][1],
                    'desconto': self.desconto,
                    'preco_final': self.preco_final,
                    'preco_inicial': self.preco_inicial}

        imagens = [{'maior': img.img_600x600.url,
                    'menor': img.img_94x94.url} for img in self.imagens.all()]

        contexto.update({'imagens': imagens})

        return contexto
Example #2
0
 def as_compact_dict(self):
     return {
         "author": self.author.pk,
         "text": self.text,
         "pub_date": _date(self.pub_date, 'd b Y г. H:i'),
         "change_date": _date(self.change_date, 'd b Y г. H:i')
     }
def twopartdate(date_start, date_end):
    """Take two datetimes and determines whether to display start and end times, or start and end dates.

    If an end date exists, we can compare the two dates.
    If the two datetimes are exactly the same, localize and print just the date.
    If the two dates are the same, localize the date for the first part and stringify the time range for the second.
    If the two dates are not the same, part 2 becomes the second date.

    If no end date exists, part 2 is just the start time.

    """
    part1 = _date(date_start, "DATE_FORMAT")
    en_dash = u'\u2013'
    if date_end:
        if date_start == date_end:
            part2 = ""
            part2_is_time = True
        elif date_start.date() == date_end.date():
            part2 = "{0}{1}{2}".format(_date(date_start, "TIME_FORMAT"),
                                       en_dash, _date(date_end, "TIME_FORMAT"))
            part2_is_time = True
        else:
            part2 = _date(date_end, "DATE_FORMAT")
            part2_is_time = False
    else:
        part2 = _date(date_start, "TIME_FORMAT")
        part2_is_time = True
    return {"part1": part1, "part2": part2, "part2_is_time": part2_is_time}
def mail(request,slug,code):
    """
        Envia i genera el pdf del justificant de Pagament a les JAEM
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)

    try:
        person = Person.objects.get(slug__iexact=slug)
    except Person.DoesNotExist:
        raise Http404

    avui = _date(datetime.now(), "d \d\e F \d\e Y")


    if person.lang == '1':
        cur_language = translation.get_language()
        try:
            translation.activate('es')
            avui = _date(datetime.now(), "d \d\e F \d\e Y")
        finally:
            translation.activate(cur_language)

    kwvars = {
        'object': person,
        'avui': avui
    }
    context = Context(kwvars)
    status = sendTemplateMail(context,code,[person.email_address])
    json = simplejson.dumps(status)
    return HttpResponse(json, mimetype='application/json')
Example #5
0
 def toDict(self):
     return {'id': self.id,
             'type':str(self),
             'durationType':self.durationType(),
             'start':_date(self.start, "H:i"),
             'stop':_date(self.stop, "H:i"),
             'cssClass':'shift_type_' + self.id}
Example #6
0
def render_appointments_table(appointments):
    rows = [(_("Date"), _("Day"), _("Time"), _("Duration"))]

    current_timezone = timezone.get_current_timezone()

    for appointment in appointments:
        localized_start_date = current_timezone.normalize(appointment.start_date.astimezone(current_timezone))
        rows.append(
            (
                _date(localized_start_date, "SHORT_DATE_FORMAT"),
                _date(localized_start_date, "l"),
                _time(localized_start_date, "TIME_FORMAT"),
                str(appointment.duration) + " " + _("min."),
            )
        )

    return {
        "title": mark_safe('<span class="glyphicon glyphicon-calendar"></span> ' + _("Appointments")),
        "summary": _("Training appointment detail"),
        "singular": _("appointment"),
        "plural": _("appointments"),
        "headers": rows.pop(0),
        "rows": rows,
        "count": len(rows),
    }
Example #7
0
def validate_birthday(birth_date):
	min_date = date(1940, 1, 1)
	max_date = date(1998, 12, 31)
	if birth_date < min_date or birth_date > max_date:
		format_min_date = _date(min_date, "d \d\e b \d\e Y")
		format_max_date = _date(max_date, "d \d\e b \d\e Y")
		raise ValidationError(u'Sólo fechas entre %s y %s' % (format_min_date, format_max_date))
Example #8
0
    def search(self, google_x, google_y, radius=None):
        "Search by coordinates, return matching items as list of dicts"

        logger.debug("google_x " + str(google_x))
        logger.debug("google_y " + str(google_y))

        rd_point_clicked = Point(*google_to_rd(google_x, google_y))
        if not self.rainapp_config:
            return None

        geo_objects = GeoObject.objects.filter(
            geometry__contains=rd_point_clicked,
            config=self.rainapp_config)

        result = []
        for g in geo_objects:
            maxdate = CompleteRainValue.objects.filter(
                parameterkey=self.parameterkey,
                config=self.rainapp_config).aggregate(
                md=Max('datetime'))['md']

            logger.debug('SEARCH maxdate = '+str(maxdate))

            if maxdate is not None:
                # If there is a maxdate, there must be a value at that date,
                # the import script should take care of that. However,
                # it can be a negative value, which is actually a statuscode.
                maxdate_site_tz = UTC.localize(maxdate).astimezone(self.tz)
                # import pdb;pdb.set_trace()
                value = g.rainvalue_set.get(datetime=maxdate,
                    parameterkey=self.parameterkey).value
                if value > -0.5:
                    popup_text = '%s: %s: %.1f mm' % (
                        g.name,
                        _date(maxdate_site_tz, "j F Y H:i").lower(),
                        value)
                else:
                    popup_text = '%s: %s: Geen data; code %i' % (
                        g.name,
                        _date(maxdate_site_tz, "j F Y H:i").lower(),
                        value)
            else:
                popup_text = '%s (Geen data)' % g.name
            identifier = {
                'location': g.municipality_id,
            }
            result.append({
                'identifier': identifier,
                'distance': 0,
                'workspace_item': self.workspace_item,
                # 'name': g.name + ' (' + str(maxdate) + ')',
                'name': popup_text,
                'shortname': g.name,
                'google_coords': (google_x, google_y),
            })

        return result
Example #9
0
def daterange_de(date_from, date_to):
    if (date_from.year == date_to.year and date_from.month == date_to.month
            and date_from.day == date_to.day):
        return str(_date(date_from, "j. F Y"))
    if date_from.year == date_to.year and date_from.month == date_to.month:
        return "{}.–{}".format(_date(date_from, "j"), _date(date_to, "j. F Y"))
    if date_from.year == date_to.year:
        return "{} – {}".format(_date(date_from, "j. F"),
                                _date(date_to, "j. F Y"))
Example #10
0
def daterange_en(date_from, date_to):
    if (date_from.year == date_to.year and date_from.month == date_to.month
            and date_from.day == date_to.day):
        return str(_date(date_from, "N jS, Y"))
    elif date_from.year == date_to.year and date_from.month == date_to.month:
        return "{} – {}".format(_date(date_from, "N jS"),
                                _date(date_to, "jS, Y"))
    elif date_from.year == date_to.year:
        return "{} – {}".format(_date(date_from, "N jS"),
                                _date(date_to, "N jS, Y"))
Example #11
0
def daterange(date_from, date_to):
    language = get_language()[:2]
    lookup = {
        "de": daterange_de,
        "en": daterange_en,
        "es": daterange_es,
    }
    function = lookup.get(language)
    result = function(date_from, date_to) if function else None
    return result or _("{date_from} – {date_to}").format(
        date_from=_date(date_from, "DATE_FORMAT"),
        date_to=_date(date_to, "DATE_FORMAT"))
Example #12
0
def daterange(date_from, date_to):
    result = None
    language = get_language()

    if language.startswith("de"):
        result = daterange_de(date_from, date_to)
    elif language.startswith("en"):
        result = daterange_en(date_from, date_to)
    elif language.startswith("es"):
        result = daterange_es(date_from, date_to)

    return result or _("{date_from} – {date_to}").format(
        date_from=_date(date_from, "DATE_FORMAT"),
        date_to=_date(date_to, "DATE_FORMAT"))
def justificantPagament(request, slug,template='contacts/person/justificant_pagament_es.pdf.html' ):
    """
        Genera el pdf del justificant de Pagament a les JAEM
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)

    user = request.user

    try:
        person = Person.objects.get(slug__iexact=slug)
    except Person.DoesNotExist:
        raise Http404

    # avui = datetime.today().strftime('%d de %B de %Y')
    avui = _date(datetime.now(), "d \d\e F \d\e Y")


    if person.lang == '1':
        cur_language = translation.get_language()
        try:
            translation.activate('es')
            avui = _date(datetime.now(), "d \d\e F \d\e Y")
        finally:
            translation.activate(cur_language)

    kwvars = {
        'object': person,
        'avui': avui
    }

    # revisam si la template ha de ser en catala
    if person.lang == '2':
        template = 'contacts/person/justificant_pagament_ca.pdf.html'


    template = get_template(template)
    context = Context(kwvars)
    html = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),
                                            dest=result,
                                            encoding='UTF-8',
                                            link_callback=fetch_resources)
    if not pdf.err:
        response = HttpResponse(result.getvalue(),mimetype='application/pdf')
        return response

    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
Example #14
0
def room_occupied(room, order=None):
    now = datetime.datetime.now()
    sps = room.specification_set.all()
    if order:
        sps = sps.filter(order=order)
    else:
        sps = sps.filter(order__state__in=settings.SELECT_WORK_ORDERS)
        sps = sps.filter(end__gte=now).order_by('end')
    try:
        sp = sps[0]
    except:
        return u''
    return u'№%s с %s по %s' % (sp.order.id,
            _date(sp.start, "d b H:i"), 
            _date(sp.end, "d b H:i"))
Example #15
0
 def get_dates_str(self):
     if self.fecha_inicio == self.fecha_fin:
         return self.fecha_fin.strftime("%-d de " +
                                        _date(self.fecha_inicio, "F") +
                                        " de %Y")
     else:
         if self.fecha_inicio.month == self.fecha_fin.month:
             return self.fecha_inicio.strftime(
                 "Del %-d ") + self.fecha_fin.strftime("al %-d de " + _date(
                     self.fecha_inicio, "F") + " de %Y")
         else:
             return self.fecha_inicio.strftime(
                 "Del %-d de " + _date(self.fecha_inicio, "F") +
                 " de %Y ") + self.fecha_fin.strftime(
                     "al %-d de " + _date(self.fecha_fin, "F") + " de %Y")
def mailJustificantPagament(request,slug):
    """
        Envia i genera el pdf del justificant de Pagament a les JAEM
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)

    try:
        person = Person.objects.get(slug__iexact=slug)
    except Person.DoesNotExist:
        raise Http404

    avui = _date(datetime.now(), "d \d\e F \d\e Y")


    if person.lang == '1':
        cur_language = translation.get_language()
        try:
            translation.activate('es')
            avui = _date(datetime.now(), "d \d\e F \d\e Y")
        finally:
            translation.activate(cur_language)

    kwvars = {
        'object': person,
        'avui': avui
    }
    # ('R', _('Registrant')) -> justpagament
    # else (convidat, organitzacio, etc) -> justregistre
    if person.contact_type == 'R':
        if person.lang == '2':
            mailtemplate = 'justpagament_cat'
        else:
            mailtemplate = 'justpagament_esp'
    else:
        if person.lang == '2':
            mailtemplate = 'justregistre_cat'
        else:
            mailtemplate = 'justregistre_esp'

    context = Context(kwvars)
    status = sendTemplateMail(context,mailtemplate,[person.email_address])
    if status == _('Mail sent'):
        person.date_mailregister = datetime.now()
        person.save()

    json = simplejson.dumps(status)
    return HttpResponse(json, mimetype='application/json')
Example #17
0
    def daily(self, request, format=None):
        now = datetime.now().timetuple()
        fmt = '%Y%m%d'
        delta = timedelta(days=1)
        range_name = 'day'

        end = request.query_params.get('end', '')
        try:
            end = datetime.strptime(end, fmt)
        except ValueError:
            end = datetime(now[0], now[1], now[2])

        begin = request.query_params.get('begin', '')
        try:
            begin = datetime.strptime(begin, fmt)
        except ValueError:
            begin = end - timedelta(days=DAILY_RANGE)

        user = request.user.userprofile
        updates_time_range = to_heatmap(
            get_syncs_time_range(begin,
                                 end + delta,
                                 range_name=range_name,
                                 user=user), range_name)

        # filling the gaps (zeros)
        data = []
        labels = []
        for item in datetime_iterator(begin, end, delta):
            labels.append(_date(item, 'Y-m-d (D)'))
            index = str(to_timestamp(datetime.combine(item, time.min)))
            data.append(updates_time_range[index] if index in
                        updates_time_range else 0)

        return Response(list(zip(labels, data)), status=status.HTTP_200_OK)
Example #18
0
    def daily(self, request, format=None):
        now = datetime.now().timetuple()
        fmt = '%Y%m%d'
        delta = timedelta(days=1)
        range_name = 'day'

        end = request.query_params.get('end', '')
        try:
            end = datetime.strptime(end, fmt)
        except ValueError:
            end = datetime(now[0], now[1], now[2])

        begin = request.query_params.get('begin', '')
        try:
            begin = datetime.strptime(begin, fmt)
        except ValueError:
            begin = end - timedelta(days=DAILY_RANGE)

        user = request.user.userprofile
        updates_time_range = to_heatmap(
            get_syncs_time_range(
                begin, end + delta, range_name=range_name, user=user
            ),
            range_name
        )

        # filling the gaps (zeros)
        data = []
        labels = []
        for item in datetime_iterator(begin, end, delta):
            labels.append(_date(item, 'Y-m-d (D)'))
            index = str(to_timestamp(datetime.combine(item, time.min)))
            data.append(updates_time_range[index] if index in updates_time_range else 0)

        return Response(zip(labels, data), status=status.HTTP_200_OK)
Example #19
0
    def form_valid(self, form):
        data = form.cleaned_data

        tee_off_time = timezone.datetime.strptime(
            '{}:{}:00'.format(form.cleaned_data['offer_tee_off_time_hour'],
                              form.cleaned_data['offer_tee_off_time_minute']),
            '%H:%M:%S').time()

        try:
            booking = models.Booking.objects.get(
                booking_uuid=form.cleaned_data['booking_uuid'])

            t = models.BookingTeeOffTime()
            t.booking = booking
            t.tee_off_time = tee_off_time
            t.status = models.BookingTeeOffTime.STATUS_CHOICES.offered
            t.save()

            data.update({
                'tee_off_time_pk': t.pk,
                'tee_off_time': tee_off_time,
                'tee_off_time_str': _date(tee_off_time, 'H:i'),
            })
        except:
            pass

        return JsonResponse(data)
Example #20
0
 def field_to_native(self, obj, field_name):
     date = getattr(obj, self.source, None)
     if date:
         date = _date(timezone.localtime(getattr(obj, self.source)),
                      settings.SHORT_DATETIME_FORMAT).replace(
                          'p.m.', 'pm').replace('a.m.', 'am')
     return date
Example #21
0
def guess(request, x, y):
    # Check if IP can make a guess
    status, key, tries_left, expires_at = process_guess(request, x, y)

    # Send this guess to everyone via WebSocket
    if status == 0:
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)('one', {
            "type": "guess",
            "x": x,
            "y": y,
            "key": key,
        })

    res = {
        "status":
        status,
        "key":
        key,
        "tries_left":
        tries_left,
        "expires_at":
        _date(timezone.localtime(expires_at), "d/m/Y H:i:s")
        if expires_at else "",
    }
    return HttpResponse(json.dumps(res), content_type="application/json")
Example #22
0
def daterange(df, dt):
    lng = get_language()

    if lng.startswith("de"):
        if df.year == dt.year and df.month == dt.month:
            return "{}.–{}".format(_date(df, "j"), _date(dt, "j. F Y"))
        elif df.year == dt.year:
            return "{} – {}".format(_date(df, "j. F"), _date(dt, "j. F Y"))
    elif lng.startswith("en"):
        if df.year == dt.year and df.month == dt.month:
            return "{} – {}".format(_date(df, "N jS"), _date(dt, "jS, Y"))
        elif df.year == dt.year:
            return "{} – {}".format(_date(df, "N jS"), _date(dt, "N jS, Y"))

    return _("{date_from} – {date_to}").format(
        date_from=_date(df, "DATE_FORMAT"), date_to=_date(dt, "DATE_FORMAT"))
Example #23
0
    def get(self, request, *args, **kwargs):
        _page = get_object_or_404(Page, pk=request.GET.get('page_id'))

        # release page for all users which did not update during the last timeframe
        PageIndicator.objects.filter(edited_on__lte=self.time_past, page=_page).delete()

        page_indicators = PageIndicator.objects.filter(edited_on__gte=self.time_past, page=_page)\
            .exclude(editor=request.user)

        response = {}
        if page_indicators.exists():
            response['conflict'] = True
            editing_user = page_indicators.first()
            response['concurrent_user'] = [editing_user.editor.username]
            # default behavior for concurrent users is blocking
            response['block_editing'] = getattr(settings, 'CONCURRENT_BLOCK_EDITING', BLOCK_EDITING_DEFAULT)

            response['message'] = _(u'Unfortunately you cannot edit this page at the moment: '
                                    u'user {user} is blocking it since {time}').format(
                    user=editing_user.editor,
                    time=_date(editing_user.started_editing, 'D, d. b, H:i'))
        else:
            response['conflict'] = False

        return JsonResponse(json.dumps(response), safe=False)
Example #24
0
    def test_tag_page(self):
        # Create the tag
        tag = Tag()
        tag.name = 'python'
        tag.description = 'The Python programming language'
        tag.save()

        # Create the author
        author = User.objects.create_user('testuser', '*****@*****.**',
                                          'password')
        author.save()

        # Create the site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()

        # Create the post
        post = Post()
        post.title = 'My first post'
        post.text = 'This is [my first blog post](http://127.0.0.1:8000/)'
        post.slug = 'my-first-post'
        post.pub_date = timezone.now()
        post.author = author
        post.site = site
        post.save()
        post.tags.add(tag)
        post.save()

        # Check new post saved
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
        only_post = all_posts[0]
        self.assertEquals(only_post, post)

        # Get the tag URL
        tag_url = post.tags.all()[0].get_absolute_url()

        # Fetch the tag
        response = self.client.get(tag_url)
        self.assertEquals(response.status_code, 200)

        # Check the tag name is in the response
        self.assertTrue(post.tags.all()[0].name.encode() in response.content)

        # Check the post text is in the response
        self.assertTrue(
            markdown.markdown(post.text).encode() in response.content)

        # Check the post date is in the response
        self.assertTrue(str(post.pub_date.year) in response.content)
        self.assertTrue(
            _date(post.pub_date, "F").encode('utf-8') in response.content)
        self.assertTrue(str(post.pub_date.day) in response.content)

        # Check the link is marked up properly
        self.assertTrue(
            '<a href="http://127.0.0.1:8000/">my first blog post</a>' in
            response.content)
 def render(self, record, table, value, bound_column, **kwargs):
     activity = record.last_for_activity_type(self.activity_type)
     if activity:
         value = _date(activity.date, "DATE_FORMAT")
     else:
         value = '—'
     return value
Example #26
0
 def get_date_to_display(self):
     if not self.show_date_to:
         return ""
     return _date(
         self.date_to,
         "DATETIME_FORMAT" if self.show_times else "DATE_FORMAT"
     )
Example #27
0
def upcoming_status(community):
    from django.template.defaultfilters import date as _date

    rows = ['', '']
    if community.upcoming_meeting_started:
        rows[0] = _("Started")
    else:
        ver = _("Version")
        if community.upcoming_meeting_published_at:
            publish_time = timezone.localtime(
                community.upcoming_meeting_published_at)
        else:
            publish_time = ''

        meeting_version = u'{0} {1} - {2}'.format(
            ver, community.upcoming_meeting_version,
            _date(publish_time, 'd F Y, H:i'))
        if community.upcoming_meeting_is_published:
            if community.straw_voting_enabled:
                if community.straw_vote_ended:
                    rows[0] = _("Straw vote ended")
                else:
                    rows[0] = _("Active straw vote")
                rows[1] = meeting_version
            else:
                rows[0] = _("Published")
                rows[1] = meeting_version
        else:
            rows[0] = _("Draft")

    return rows
Example #28
0
    def get(self, request, pk):
        reunion = self.get_object(Reunion, pk=self.kwargs['pk'])
        reunion.estado_reunion = 'CONV'
        reunion.save()
        ordenes = Orden.objects.filter(reunion=reunion)
        puntos = ''
        for orden in ordenes:
            orden.punto.estado_punto_anterior = orden.punto.estado_punto
            orden.punto.estado_punto = 'CONV'
            orden.punto.save()
            puntos = puntos + '- ' + orden.punto.nombre_admin + '.\n'

        destinatarios = lista_miembros_organo_email(
            self.request.session.get('organo'))
        #print(destinatarios)
        Organo = self.request.session.get('organo')

        Asunto = 'Convocada Reunion del ' + Organo + '.'
        Texto = 'Estimado miembro del '+Organo+',\n\n' \
                                               'Se ha convocado una Reunion para la fecha: \n'\
                +unicode(_date(reunion.fecha_hora, 'l d F Y H:i'))+\
                '\nen '+reunion.lugar+', en la que se trataran los siguientes puntos del dia: \n'+puntos+\
                '\nEsperamos su asistencia.\n\nReciba un cordial saludo y muchas gracias.\n\n\nMensaje generado automaticamente, por favor, no lo responda.'
        email = EmailMessage(Asunto,
                             Texto,
                             to=['*****@*****.**'])
        email.send()

        return HttpResponseRedirect(reverse_lazy('reunion_detail', args=[pk]))
Example #29
0
    def get(self, request, pk):
        reunion = self.get_object(Reunion, pk=self.kwargs['pk'])
        reunion.estado_reunion = 'CRE'
        reunion.save()
        ordenes = Orden.objects.filter(reunion=reunion)
        for orden in ordenes:
            if orden.punto.estado_punto_anterior:
                orden.punto.estado_punto = orden.punto.estado_punto_anterior
            else:
                orden.punto.estado_punto = 'ADD'
            orden.punto.save()
        destinatarios = lista_miembros_organo_email(
            self.request.session.get('organo'))
        # print(destinatarios)
        Organo = self.request.session.get('organo')

        Asunto = 'Desconvocada Reunion del ' + Organo + '.'
        Texto = 'Estimado miembro del ' + Organo + ',\n\n' \
                                                   'Se ha desconvocado la Reunion de la fecha: \n' \
                + unicode(_date(reunion.fecha_hora, 'l d F Y H:i')) + \
                '\nen ' + reunion.lugar + '.\nPor favor, elimine la cita de su agenda, sentimos mucho los inconvenientes ocasionados.' \
                                          '\n\nReciba un cordial saludo y muchas gracias.\n\n\nMensaje generado automaticamente, por favor, no lo responda.'
        email = EmailMessage(Asunto,
                             Texto,
                             to=['*****@*****.**'])
        email.send()
        return HttpResponseRedirect(reverse_lazy('reunion_detail', args=[pk]))
Example #30
0
    def get(self, request, *args, **kwargs):
        _page = get_object_or_404(Page, pk=request.GET.get('page_id'))

        # release page for all users which did not update during the last timeframe
        PageIndicator.objects.filter(edited_on__lte=self.time_past, page=_page).delete()

        page_indicators = PageIndicator.objects.filter(edited_on__gte=self.time_past, page=_page) \
            .exclude(editor=request.user)

        response = {}
        if page_indicators.exists():
            response['conflict'] = True
            editing_user = page_indicators.first()
            response['concurrent_user'] = [editing_user.editor.username]
            # default behavior for concurrent users is blocking
            response['block_editing'] = getattr(settings, 'CONCURRENT_BLOCK_EDITING', BLOCK_EDITING_DEFAULT)

            response['message'] = _(u'The page is currently edited by {user} since {time}.') \
                .format(user=editing_user.editor, time=_date(editing_user.started_editing, 'D, d. b, H:i'))
            response['buttons'] = {
                'published_page': {
                    'link': '{url}?edit_off'.format(url=_page.get_absolute_url()),
                    'link_text': _('View Published Page'),
                },
                'back': {
                    'link': '',
                    'link_text': _('Back'),
                }
            }
        else:
            response['conflict'] = False

        return JsonResponse(json.dumps(response), safe=False)
Example #31
0
def render_trainings_table(trainings):
    rows = [(_("Detail"), _("Training name"), _("Start date"))]

    current_timezone = timezone.get_current_timezone()

    for training in sorted(trainings, key=lambda training: training.get_start_date()):
        localized_start_date = current_timezone.normalize(training.get_start_date().astimezone(current_timezone))
        rows.append(
            (
                mark_safe(
                    '<a class="btn btn-success btn-xs" href="'
                    + reverse("training-detail", args=[training.id])
                    + '" title="'
                    + _("Show training details")
                    + '"><span class="glyphicon glyphicon-calendar"></span></a>'
                ),
                training.title,
                _date(localized_start_date, "DATE_FORMAT"),
            )
        )

    return {
        "title": _("Next upcoming trainings"),
        "summary": _("Training overview"),
        "singular": _("training"),
        "plural": _("trainings"),
        "headers": rows.pop(0),
        "rows": rows,
        "count": len(rows),
    }
Example #32
0
def render_attendances_table(attendances):
    rows = [(
        _("Title"),
        _("Start date"),
        _("State"),
    ),]
    
    current_timezone = timezone.get_current_timezone()
    
    for attendance in attendances:
        localized_start_date = current_timezone.normalize(attendance.training.get_start_date().astimezone(current_timezone))
        rows.append((
            mark_safe("<a href=\"" + reverse("training-detail", args=[attendance.training.id]) + "\">" + attendance.training.title + "</a>"),
            _date(localized_start_date, "SHORT_DATE_FORMAT"),
            attendance.states.get().get_state(),
        ),)
    
    return {
        "title": mark_safe("<span class=\"glyphicon glyphicon-calendar\"></span> " + _("Attendances")),
        "summary": _("Your training attendances"),
        "singular": _("attendance"),
        "plural": _("attendances"),
        "headers": rows.pop(0),
        "rows": rows,
        "count": len(rows),
    }
Example #33
0
    def get(self, request, *args, **kwargs):
        from django.template.defaultfilters import date as _date
        from django.conf import settings
        slug = kwargs.get("slug", None)
        agent = Agent.objects.get(slug=slug)
        pk = int(kwargs.get("pk")) if kwargs.get("pk", None) else None
        from django.core.serializers.json import DjangoJSONEncoder
        
        if pk:
            logs = agent.logs.filter(pk__gt = pk)
        else:
            logs = agent.logs.all()
        
        data = {"logs": [], 'pk': None}
        total = logs.count()

        if total:
            if not pk:
                logs = logs[total-11:]
            else:
                logs = logs[:10]
            total = logs.count()
            data["pk"] = logs[total-1].pk
            for log in logs:
                data["logs"].append({'pk': log.pk, 'date': _date(log.date, settings.SHORT_DATETIME_FORMAT), 'message': log.message})
        data = simplejson.dumps(data, cls=DjangoJSONEncoder)
            
        return HttpResponse(data, content_type='application/json')
Example #34
0
    def prepare_reference_title(self, obj):
        '''
        Used for search purpose, index act title different languages
        '''
        ref_title_list = []
        act_type_trans = obj.act_type.get_translations()

        if not obj.title:
            if obj.issue_date:
                for act_type in act_type_trans:
                    act_type_lang = act_type.split('^')[0]
                    act_type_label = act_type.split('^')[1]
                    activate(act_type_lang)
                    act_date = _date(obj.issue_date, "d \d\e F \d\e Y")

                    act_title = u"{0} Nº {1} - {2}".format(
                        act_type_label, obj.act_number, act_date)
                    ref_title_list.append(act_title)
            else:
                for act_type in act_type_trans:
                    act_type_label = act_type.split('^')[1]
                    act_title = u"{0} Nº {1}".format(act_type_label,
                                                     obj.act_number)
                    ref_title_list.append(act_title)

        return ref_title_list
Example #35
0
def notification_call(request):
    students = Student.objects.all()
    messages = str()

    for student in students:
        notification_message = "<h4>Hej {},</h4><br>".format(
            student.user.first_name)
        notification_message += "<h4>Kroz idućih 7 dana na redu su sljedeće aktivnosti:</h4><br><ul>"

        due_activities = list()
        for subject in student.subjects:
            due_activities += subject.upcoming_score_activities(student)

        if due_activities:
            for activity in due_activities:
                notification_message += "<li>{} - {}, {}</li>".format(
                    activity.get_type_display(), activity.subject,
                    _date(activity.due_date, "l d.m.Y"))
        else:
            notification_message += "<li>Ovog tjedna nema ispitnih aktivnosti</li>"
        notification_message += "</ul><br>"
        notification_message += "<h4>Puno uspjeha u narednom tjednu!</h4>"
        notification_message += "<h5>Srdačan pozdrav od Timetabled tima</h5>"
        messages += notification_message
        send_mail(
            subject='Timetabled - tjedna obavijest',
            message="",
            html_message=notification_message,
            from_email=settings.EMAIL_HOST_USER,
            recipient_list=[student.user.email],
        )
    return HttpResponse(messages)
Example #36
0
 def get_time_from_display(self, tz=None) -> str:
     """
     Returns a formatted string containing the start time of the event, ignoring
     the ``show_times`` setting.
     """
     tz = tz or self.timezone
     return _date(self.date_from.astimezone(tz), "TIME_FORMAT")
    def handle_noargs(self, **options):
        print "Testing"
        person_list = Person.objects.all()
        # person_list = person_list.filter(status='ok_all')
        person_list = person_list.filter(date_modified__gt=datetime.today() - timedelta(days=3))

        translation.activate('es')
        avui = _date(datetime.now(), "d \d\e F \d\e Y")


        for person in person_list:
            for course in person.courses.all():

                context = {
                    'object' : person,
                    'course' : course,
                    'avui' : avui
                }
                output_filename = 'generated_files/fitxaMEC/%s_ficha_participantes_%s.pdf' % (course.code, person.slug)
                if not os.path.isfile(output_filename):
                    html = render_to_string('contacts/person/ficha_participantes_mec.html',context)
                    result = file(output_filename,'wb')
                    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),
                                                            dest=result,
                                                            link_callback=fetch_resources)
                    result.close()
                    print "%s generated" % output_filename

                    if pdf.err:
                        raise Exception('Error generating pdf. %d errors' % pdf.err )
Example #38
0
    def registration_date(self, obj):
        if obj.registration_start is not None:
            start_date = timezone.make_naive(obj.registration_start)
        else:
            start_date = obj.registration_start

        return _date(start_date, "l d b Y, G:i")
Example #39
0
    def construct_file_path(self,
                            storage_directory=STORAGE_DIRECTORY,
                            naming_scheme=DEFAULT_NAMING_SCHEME,
                            inpath_dateformat=DEFAULT_DATE_FORMAT):
        linkpath, extension = strip_url(self.media_url)

        info = {}
        for key, value in AVAILABLE_EPISODE_SEGMENTS.items():
            info[key] = getattr(self, value, '')

            if key == 'episode_id':
                info[key] = str(info[key])
            elif key == 'podcast_updated' or key.endswith('_date'):
                info[key] = _date(info[key], inpath_dateformat)
            if info[key] is None:
                info[key] = ''

        for key, value in AVAILABLE_PODCAST_SEGMENTS.items():
            info[key] = getattr(self.podcast, value, '')

            if info[key] is None:
                info[key] = ''

        filename = Template(naming_scheme)
        filename = filename.safe_substitute(info)

        self.file_path = os.path.join(storage_directory, filename + extension)
        self.save()
        return self.file_path
Example #40
0
 def prepare_message(self, message):
     html_message = message.replace("\r\n", "<br />")
     survey_link = "".join(
             [
                 self.questionnaire.mail_config.domain,
                 reverse("django_survey:answer", args=(self.token,))
             ]
         )
     html_message = html_message.replace(
         "#LINK#",
         '<a href="%s">lien vers l\'enquête</a>' % survey_link)
     html_message = html_message.replace(
         "#SUBJECT#",
         self.subject)
     html_message = html_message.replace(
         "#DATE#",
         _date(self.event_date, "d F Y"))
     html_message = html_message.replace(
         "#TITLE#",
         self.title)
     html_message = html_message.replace(
         "#FIRSTNAME#",
         self.firstname)
     html_message = html_message.replace(
         "#LASTNAME#",
         self.lastname)
     return html_message
Example #41
0
def upcoming_status(community):
    from django.template.defaultfilters import date as _date
    
    rows = ['', '']
    if community.upcoming_meeting_started:
        rows[0] = _("Started")
    else:
        ver = _("Version")
        if community.upcoming_meeting_published_at:
            publish_time = timezone.localtime(
                    community.upcoming_meeting_published_at)
        else:
            publish_time = ''
            
        meeting_version = u'{0} {1} - {2}'.format(ver,
                            community.upcoming_meeting_version,
                            _date(publish_time, 'd F Y, H:i'))
        if community.upcoming_meeting_is_published:
            if community.straw_voting_enabled:
                if community.straw_vote_ended:
                    rows[0] = _("Straw vote ended")
                else:
                    rows[0] = _("Active straw vote")
                rows[1] = meeting_version
            else:
                rows[0] = _("Published")
                rows[1] = meeting_version
        else:
            rows[0] = _("Draft")

    return rows
Example #42
0
 def __unicode__(self):
     try:
         return _('%(description)s since %(date_start)s') % {
             'description': self.get_event()().get_description(self),
             'date_start': _date(self.date_start, 'd F Y'),
             }
     except TypeError:
         return _('error')
Example #43
0
    def date_represenation(self):

        if self.duration == 1:

            start = self.date

            return _date(start, 'd F Y')

        else:
            end = self.end_date()
            start = self.date

            if start.month == end.month:
                return _date(start, 'd') + ' - ' + _date(end, 'd F Y')

            else:
                return _date(start, 'd F') + ' - ' + _date(end, 'd F')
Example #44
0
def get_serialized_comment(comment):
    """
    Get a dict of comment instance.
    :param comment: Comment instance.
    :return: a dict representation of a comment.
    """
    return {
        'pk': comment.pk,
        'text': comment.text,
        'author': comment.user.username,
        'publication_date': _date(comment.publication_date),
        'publication_time': _time(comment.publication_date),
        'last_update_date': _date(comment.last_update),
        'last_update_time': _time(comment.last_update),
        'update_url': comment.update_url

    }
    def handle_noargs(self, **options):
        print "Enviament confirmacio inscripcio ok"

        person_list = Person.objects.all()
        person_list = person_list.filter(date_mailregister__isnull = True, status='ok_all')[:5]

        for person in person_list:
            print person.fullname
            avui = _date(datetime.now(), "d \d\e F \d\e Y")
            cur_language = translation.get_language()

            try:
                if person.lang == '2':
                    translation.activate('ca')
                    avui = _date(datetime.now(), "d \d\e F \d\e Y")
                else:
                    translation.activate('es')
                    avui = _date(datetime.now(), "d \d\e F \d\e Y")
            finally:
                translation.activate(cur_language)

            kwvars = {
                'object': person,
                'avui': avui
            }
            # ('R', _('Registrant')) -> justpagament
            # else (convidat, organitzacio, etc) -> justregistre
            if person.contact_type == 'R':
                if person.lang == '2':
                    mailtemplate = 'justpagament_cat'
                else:
                    mailtemplate = 'justpagament_esp'
            else:
                if person.lang == '2':
                    mailtemplate = 'justregistre_cat'
                else:
                    mailtemplate = 'justregistre_esp'

            context = Context(kwvars)
            status = sendTemplateMail(context,mailtemplate,[person.email_address])
            if status == _('Mail sent'):
                person.date_mailregister = datetime.now()
                person.save()
                print "Mail sended to %s" % person.email_address
            else:
                print "Error ocurred sendint to %s. Error message: %s" % (excursion.email_address, status )
Example #46
0
 def get_date_from_display(self) -> str:
     """
     Returns a formatted string containing the start date of the event with respect
     to the current locale and to the ``show_times`` setting.
     """
     return _date(
         self.date_from,
         "DATETIME_FORMAT" if self.settings.show_times else "DATE_FORMAT")
Example #47
0
    def to_dict(self, modal=False):
        imagem = None
        images = self.imagens.all()
        if self.tipo == Oferta.OFERTA:
            if images and images[0].imagem:
                imagem = images[0].img_172x172.url
        elif self.tipo == Oferta.EVENTO:
            if images:
                imagem = images[0].evento_180x445.url
        else:
            if images:
                imagem = images[0].img_376x376.url

        contexto = {'id': str(self.id),
                    'unicode': self,
                    'loja': self.loja.to_dict() if self.loja else None,
                    'descricao': self.descricao,
                    'texto_do_link': self.texto_link,
                    'chamada_promocional': self.texto_promocional,
                    'imagem': imagem,
                    'compartilhamentos': self.total_visto,
                    'curtidas': self.total_curtido,
                    'categoria': [c.to_dict() for c in self.categoria.all()],
                    'expira': self.expira,
                    'expira_str': self.expira_str,
                    'titulo': self.nome,
                    'tipo': Oferta.TIPOS[self.tipo][1] if self.tipo else None,
                    'inicio': _date(self.inicio, 'd/m/Y'),
                    'fim': _date(self.fim, 'd/m/Y'),
                    'fim_curto': _date(self.fim, 'd/m'),
                    'genero': self.GENEROS[self.genero][1] if self.genero in [0, 1, 2, 3] else None,
                    'porcentagem': self.porcentagem_desconto(),
                    'desconto': self.desconto,
                    'cupom': True if self.subtipo == self.CUPOM else False}

        if not self.tipo == Oferta.EVENTO:
            contexto.update({'preco_final': self.preco_final,
                             'preco_inicial': self.preco_inicial})

        if modal:
            imagens = [{'maior': img.img_600x600.url,
                        'menor': img.img_94x94.url} for img in images]
            contexto.update({'descricao': self.descricao,
                             'imagens': imagens})
        return contexto
Example #48
0
File: utils.py Project: Junar/datal
 def default(self, obj):
     if hasattr(obj, "strftime"):
         return string.capitalize(_date(obj, "F d, Y, h:i A"))
     elif isinstance(obj, decimal.Decimal):
         return float(obj)
     elif isinstance(obj, ModelState):
         return None
     else:
         return json.JSONEncoder.default(self, obj)
Example #49
0
 def get_time_from_display(self, tz=None) -> str:
     """
     Returns a formatted string containing the start time of the event, ignoring
     the ``show_times`` setting.
     """
     tz = tz or self.timezone
     return _date(
         self.date_from.astimezone(tz), "TIME_FORMAT"
     )
Example #50
0
 def get_short_date_from_display(self, tz=None, show_times=True) -> str:
     """
     Returns a shorter formatted string containing the start date of the event with respect
     to the current locale and to the ``show_times`` setting.
     """
     tz = tz or self.timezone
     return _date(
         self.date_from.astimezone(tz), "SHORT_DATETIME_FORMAT"
         if self.settings.show_times and show_times else "DATE_FORMAT")
Example #51
0
 def get_date_from_display(self) -> str:
     """
     Returns a formatted string containing the start date of the event with respect
     to the current locale and to the ``show_times`` setting.
     """
     return _date(
         self.date_from,
         "DATETIME_FORMAT" if self.settings.show_times else "DATE_FORMAT"
     )
Example #52
0
 def get_date_from_display(self, tz=None, show_times=True) -> str:
     """
     Returns a formatted string containing the start date of the event with respect
     to the current locale and to the ``show_times`` setting.
     """
     tz = tz or self.timezone
     return _date(
         self.date_from.astimezone(tz),
         "DATETIME_FORMAT" if self.settings.show_times and show_times else "DATE_FORMAT"
     )
Example #53
0
 def get_date_range_display(self, tz=None) -> str:
     """
     Returns a formatted string containing the start date and the end date
     of the event with respect to the current locale and to the ``show_times`` and
     ``show_date_to`` settings.
     """
     tz = tz or self.timezone
     if not self.settings.show_date_to or not self.date_to:
         return _date(self.date_from.astimezone(tz), "DATE_FORMAT")
     return daterange(self.date_from.astimezone(tz), self.date_to.astimezone(tz))
Example #54
0
    def __unicode__(self):
        if self.title:
            act_title = self.title
        else:
            if self.issue_date:
                act_date = _date(self.issue_date, "d \d\e F \d\e Y")
                act_title = u"{0} {1}, de {2}".format(self.act_type, self.act_number, act_date)
            else:
                act_title = u"{0} {1}".format(self.act_type, self.act_number)

        return act_title
def mailJustificantPagamentExcursion(request,id):
    """
        Envia i genera el pdf del justificant de Pagament del sopar de les JAEM
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)

    try:
        excursion = Excursion.objects.get(id=id)
    except Excursion.DoesNotExist:
        raise Http404

    avui = _date(datetime.now(), "d \d\e F \d\e Y")


    if excursion.person and excursion.person.lang == '1':
        cur_language = translation.get_language()
        try:
            translation.activate('es')
            avui = _date(datetime.now(), "d \d\e F \d\e Y")
        finally:
            translation.activate(cur_language)

    kwvars = {
        'object': excursion,
        'avui': avui
    }

    if excursion.person and excursion.person.lang == '2':
        mailtemplate = 'exc_justpagament_cat'
    else:
        mailtemplate = 'exc_justpagament_esp'

    context = Context(kwvars)
    status = sendTemplateMail(context,mailtemplate,[excursion.email_address])
    if status == _('Mail sent'):
        excursion.date_mailregister = datetime.now()
        excursion.save()

    json = simplejson.dumps(status)
    return HttpResponse(json, mimetype='application/json')
Example #56
0
 def get_date_to_display(self) -> str:
     """
     Returns a formatted string containing the start date of the event with respect
     to the current locale and to the ``show_times`` setting. Returns an empty string
     if ``show_date_to`` is ``False``.
     """
     if not self.settings.show_date_to:
         return ""
     return _date(
         self.date_to,
         "DATETIME_FORMAT" if self.settings.show_times else "DATE_FORMAT"
     )
Example #57
0
def circled(value, args=''):
    """
    Surround value with a circle,
    if value is a Date type, has specific styles
    {{ act.presentation_date|circled }}
    {{ act.presentation_date|circled:"full" }}
    {{ act.presentation_date|circled:"colored" }}
    {{ act.presentation_date|circled:"full,colored" }}
    NOTE: Works with .circle styles

    """
    colored = 'colored' in args
    full = 'full' in args
    dark = 'dark' in args
    voteok = 'voteok' in args
    voteko = 'voteko' in args

    classes = []
    if type(value).__name__=='date':
        if full:
            classes.append('circle-fulldate')
            value = "<span class=\"day\">%s</span> <span class=\"month\">%s</span> <span class=\"year\">%s</span>" %\
                    (_date(value, "d"), _date(value, "b"), _date(value, "Y"))
        else:
            classes.append('circle-date')
            value = "<span class=\"day\">%s</span> <span class=\"month\">%s</span>" %\
                    (_date(value, "d"), _date(value, "b"))
    else:
        classes.append('circle')

    if colored:
        classes.append('circle-colored')
    elif dark:
        classes.append('circle-dark')
    elif voteok:
        classes.append('circle-green')
    elif voteko:
        classes.append('circle-red')

    return mark_safe('<div class="%s">%s</div>' %  (' '.join(classes), value))
Example #58
0
 def get_short_date_to_display(self, tz=None) -> str:
     """
     Returns a shorter formatted string containing the start date of the event with respect
     to the current locale and to the ``show_times`` setting. Returns an empty string
     if ``show_date_to`` is ``False``.
     """
     tz = tz or self.timezone
     if not self.settings.show_date_to or not self.date_to:
         return ""
     return _date(
         self.date_to.astimezone(tz),
         "SHORT_DATETIME_FORMAT" if self.settings.show_times else "DATE_FORMAT"
     )