Example #1
0
 def send_notice(self):
     if self.post != None:
         film = list(self.post.related_film.all()[0:1])
         film = film and film[0]
         person = list(self.post.related_person.all()[0:1])
         person = person and person[0]
         object = film or person
         send([self.user], "useractivity_post", {
             'post':self.post,
             'link':self.post.get_absolute_url(),
             'picture':object and object.get_absolute_image_url() or '',
             'film':film,
             'film_kind': gettext("TV series") if film and film.is_tv_series else gettext("film"),
             'person':person,
             'object':object,
             'hashtags': self.get_hashtags(film),
         })
     elif self.short_review != None:
         # TODO write notifications for wall posts!
         if self.short_review.object is not None and \
            self.short_review.object.type == Object.TYPE_FILM:
             self.object = self.short_review.parent
             self.watching_object = self.short_review.parent
             send([self.user], "useractivity_short_review", {
                 'short_review':self.short_review,
                 'link':self.short_review.get_absolute_url(),
                 'picture':self.short_review.object.film.get_absolute_image_url(),
                 'film':self.short_review.object.film,
                 'hashtags': self.get_hashtags(self.short_review.object.film)
             })
     elif self.comment != None:
         # for comments, create notification objects!
         Watching.create_notices(self)
    def _get_filter_description(self):
        if self.cleaned_data:
            search_description = self.cleaned_data.get('search')

            def get_date(date_key):
                date = self.cleaned_data.get(date_key)
                if date:
                    return format_date(date, 'd/m/Y')

            date_range = {
                'start': get_date('start'),
                'end': get_date('end'),
            }
            if date_range['start'] and date_range['end']:
                if date_range['start'] == date_range['end']:
                    date_range_description = gettext('on %(start)s') % date_range
                else:
                    date_range_description = gettext('between %(start)s and %(end)s') % date_range
            elif date_range['start']:
                date_range_description = gettext('since %(start)s') % date_range
            elif date_range['end']:
                date_range_description = gettext('up to %(end)s') % date_range
            else:
                date_range_description = None
        else:
            search_description = None
            date_range_description = None
        return search_description, date_range_description
def recuperar_cuenta(request):
    if request.method=="POST":
        txt_username=request.POST['txt_username']
        txt_email=request.POST['txt_email']
        if User.objects.filter(email=txt_email, username=txt_username, is_active=True).exists():
            id_usuario=User.objects.get(username=txt_username, email=txt_email)
            asunto= gettext("Recuperar Cuenta Dyuyay Local").decode('utf-8')
            text_content= ""
            html_content = "<div style='color:#ffffff;background-color: #253561;background-image: url(http://drive.google.com/uc?export=view&id=0B1kIyBXgMcA2RzNDQ2ZiTjlYYWc);width: 100%'>" \
                            "<h3 style='padding-top: 1%;padding-bottom: 1%' align='center'>Recuperar Cuenta Dyuyay Local " \
                            "<img align='center' src='http://drive.google.com/uc?export=view&id=0B1kIyBXgMcA2NmFoWUYwWjRUVWc' width='40px' height='50px'/>" \
                            "</h3><p>Nuestro servidores han recibido la solicitud para recuperar tu cuenta, si tu has realizado esta solicitud da clic " \
                            "<a href='http://"+request.get_host()+"/recuperar_cuenta/"+str(id_usuario.id)+"/"+str(txt_username)+"/"+str(txt_email)+"/' style='color: red' >en este enlace</a>" \
                            "caso contrario ignora el mismo.</p><p>Dyuyay estamos orgullos de servirte, no olvides visitar tu espacio WEB en " \
                            "<a href='http://190.154.40.195/' style='color: #ffffff'>Dyuyay</a>mas datos si se desea" \
                            "</p></div>"
            mail=EmailMultiAlternatives(asunto, text_content, to=[txt_email])
            mail.attach_alternative(html_content, "text/html")
            try:
                mail.send()
                messages.add_message(request, messages.SUCCESS, gettext("Verifique su correo electrónico").decode('utf-8'))
            except:
                messages.add_message(request, messages.ERROR, gettext("Verifique su conexion a internet").decode('utf-8'))
        else:
            messages.add_message(request, messages.ERROR, gettext("Correo electrónico y nombre de usuario incorrectos").decode('utf-8'))
    return redirect('/')
Example #4
0
def notes_add_category(request):
    ret = {}
    if request.user.is_authenticated():
        parent = request.POST.get("category", None)
        new_category = request.POST.get("new_category", '').strip()
        if new_category:
            try:
                parent = ZornaNoteCategory.objects.get(
                    pk=parent, owner=request.user)
            except:
                parent = None
            category = ZornaNoteCategory(name=new_category, slug=slugify(
                new_category), owner=request.user)
            if parent:
                category.parent = parent
            category.save()
            ret['status'] = 'success'
            ret['message'] = gettext(u'Category created successfully')
            parents = [str(c.pk) for c in category.get_ancestors()]
            rel = '/'.join(parents) + '/' + str(category.pk) + '/'
            ret['url'] = '<li class="directory collapsed"><a href="#" id="%s" rel="%s">%s</a></li>' % (
                category.pk, rel, new_category)
        else:
            ret['status'] = 'error'
            ret['message'] = gettext(u'You must give a valid name')
    else:
        ret['status'] = 'error'
        ret['message'] = gettext(u'Access denied')
    return HttpResponse(simplejson.dumps(ret))
def credit_group_title_for_sender(context):
    request = context.get('request')
    if not request:
        return ''

    sender_name = request.GET.get('sender_name')
    if sender_name:
        credit_group_title = gettext('Sender %(sender_name)s') % {'sender_name': sender_name}
    else:
        credit_group_title = gettext('Unknown sender')

    sender_sort_code = request.GET.get('sender_sort_code', '')
    if sender_sort_code:
        sender_sort_code = format_sort_code(sender_sort_code)
    sender_account_number = request.GET.get('sender_account_number', '')
    sender_roll_number = request.GET.get('sender_roll_number', '')
    if sender_account_number and sender_roll_number:
        sender_account_number = '%s/%s' % (sender_account_number, sender_roll_number)
    sender_account = ('%s %s' % (sender_sort_code, sender_account_number)).strip()
    if sender_account:
        credit_group_title = escape(credit_group_title)
        sender_account = escape(sender_account)
        credit_group_title = mark_safe('%s<br>\n<small>%s</small>' % (credit_group_title, sender_account))

    return credit_group_title
Example #6
0
 def to_python(self, value):
     if value is None:
         return value
     try:
         return int(value)
     except (TypeError, ValueError):
         raise validators.ValidationError, gettext("This value must be an integer.")
Example #7
0
 def to_python(self, value):
     if value is None:
         return value
     try:
         return decimal.Decimal(value)
     except decimal.InvalidOperation:
         raise validators.ValidationError, gettext("This value must be a decimal number.")
    def get_search_description(self):
        if self.pagination['full_count']:
            credit_description = ngettext(
                '%(count)s credit',
                '%(count)s credits',
                self.pagination['full_count'],
            ) % {'count': '<strong>{:,}</strong>'.format(self.pagination['full_count'])}
        else:
            return gettext('No credits found')

        search_description, date_range_description = self._get_filter_description()
        if date_range_description:
            description = gettext('Showing %(credits)s received %(date_range)s') % {
                'date_range': date_range_description,
                'credits': credit_description,
            }
        elif search_description:
            description = gettext('Showing %(credits)s received') % {
                'credits': credit_description,
            }
        else:
            description = gettext('Showing all %(credits)s received') % {
                'credits': credit_description,
            }
        return mark_safe(description)
Example #9
0
    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        For example, if this MultiValueField was instantiated with
        fields=(DateField(), TimeField()), clean() would call
        DateField.clean(value[0]) and TimeField.clean(value[1]).
        """
        clean_data = []
        errors = ErrorList()
        if self.required and not value:
            raise ValidationError(gettext(u'This field is required.'))
        elif not self.required and not value:
            return self.compress([])
        if not isinstance(value, (list, tuple)):
            raise ValidationError(gettext(u'Enter a list of values.'))
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None
            if self.required and field_value in EMPTY_VALUES:
                raise ValidationError(gettext(u'This field is required.'))
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError, e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(e.messages)
    def render(self, context):
        message = resolve_variable(self.message, context)

        if not message:
            return ''

        user = context.get('user', None)
        request = context.get('request', None)
        
        if (request is None) or (user is None):
            if settings.DEBUG:
                print 'TRANSLATE: user or request not found!'
            return ''

        untrans = Message.objects.get_untranslated_for(message)
        
        path = '?' + urllib.urlencode({'next': request.path})        
        translate = gettext('translate to')
        digest = message_digest(self.message)
        MR = settings.MEDIA_URL.rstrip('/')
        translate_root = getattr(settings, 'TRANSLATE_ROOT', '/translate').rstrip('/')

        if len(untrans):
            ret = ['<ul class="untranslated">']
            for un in untrans:
                name = gettext(get_language_name(un))
                flag = '<img src="%(MR)s/img/flags/%(un)s.png" alt="%(name)s" title="%(translate)s %(name)s" style="vertical-align: middle;" />' % locals()
                lnk = '<a href="%(translate_root)s/translate/%(digest)s/%(un)s/%(path)s" class="translation" rel="nofollow"">%(flag)s</a>' % locals()
                ret.append('<li>%s</li>' % lnk)
            ret.append('</ul>')
            return ''.join(ret)
        else:
            return ''
 def add_failed_attempt(self, user, client):
     self.get_queryset().create(
         user=user,
         application=client,
     )
     failed_attempts = self.get_queryset().filter(user=user, application=client)
     if failed_attempts.count() == settings.MTP_AUTH_LOCKOUT_COUNT:
         roles = Role.objects.get_roles_for_user(user)
         roles = list(filter(lambda role: role.application == client, roles))
         if roles:
             service_name = client.name.lower()
             login_url = roles[0].login_url
         else:
             service_name = gettext('Prisoner Money').lower()
             login_url = None
         email_context = {
             'service_name': service_name,
             'lockout_period': settings.MTP_AUTH_LOCKOUT_LOCKOUT_PERIOD // 60,
             'login_url': login_url,
         }
         send_email(
             user.email, 'mtp_auth/account_locked.txt',
             capfirst(gettext('Your %(service_name)s account is temporarily locked') % email_context),
             context=email_context, html_template='mtp_auth/account_locked.html',
             anymail_tags=['account-locked'],
         )
Example #12
0
    def build_slack_attachment_from_feedback(self, feedback):
        """
        Build a Slack attachment entity from the given Feedback object.

        :param feedback: Feedback object
        :type feedback: feedback.models.Feedback
        :return: Slack attachment dictionary
        :rtype: dict
        """
        attachment = {
            'text': feedback.body,
            'ts': int(feedback.created_at.timestamp()),
        }
        attachment['fields'] = fields = []
        # If the feedback refers to a Wagtail Page, add some more
        # information to the Slack notification.
        try:
            Page = apps.get_model('wagtailcore', 'Page')
            klass = feedback.content_type.model_class()
            if issubclass(klass, Page):
                page = Page.objects.get(id=feedback.object_id)
                attachment['title'] = page.title
                attachment['title_link'] = page.full_url
        except (LookupError, ObjectDoesNotExist):
            pass
        with translation.override(self.language):
            if feedback.name:
                fields.append({'title': gettext('Name'), 'value': feedback.name, 'short': False})
            if feedback.email:
                fields.append({'title': gettext('Email'), 'value': feedback.email, 'short': False})
            if feedback.user_agent:
                fields.append({'title': gettext('User agent'), 'value': feedback.user_agent, 'short': False})
        return attachment
Example #13
0
File: views.py Project: kamni/zorna
def fm_delete_file(request):
    pathfile = request.POST.get('dir', None)
    ret = {}
    if pathfile:
        path = clean_path(pathfile)
        if path != pathfile:
            ret['message'] = gettext(u"Incorrect path")
            ret['status'] = 'error'
        else:
            buser, bmanager = get_user_access_to_path(request.user, path)
            if bmanager is False:
                ret['message'] = gettext(u"Access denied")
                ret['status'] = 'error'
            else:
                try:
                    fname = os.path.basename(pathfile)
                    pk, filename = split_file_name(fname)
                    os.remove(get_upload_library() + '/' + path)
                    ZornaFile.objects.get(pk=int(pk)).delete()
                    ret['message'] = gettext(u"File deleted successfully")
                    ret['status'] = 'success'
                except:
                    ret['message'] = gettext(u"Invalid file name")
                    ret['status'] = 'error'
    else:
        ret['message'] = gettext(u"Invalid file path")
        ret['status'] = 'error'

    json_data = simplejson.dumps(ret)
    return HttpResponse(json_data)
Example #14
0
File: views.py Project: kamni/zorna
def fm_manage_folder(request):
    ret = {'data': ''}
    if request.method == 'POST':
        what = request.POST.get('what', '')
        ppath = request.POST.get('path_rel', '')
        ppath = urllib.unquote(ppath.rstrip('/'))
        folder_dest = clean_path(ppath)
        buser, bmanager = get_user_access_to_path(request.user, folder_dest)
        if folder_dest and bmanager:
            root_path = get_upload_library()
            path_dest = clean_path(folder_dest)
            parts = path_dest.split('/')
            if what == 'rename' and len(parts) > 1:
                new_folder = request.POST.get('new_folder', '').strip()
                n_folder = clean_path(new_folder)
                if new_folder == n_folder:
                    try:
                        n_folder = urllib.unquote(n_folder)
                        path_src = u"%s/%s" % (
                            root_path, urllib.unquote(path_dest))
                        dest = parts[:-1]
                        dest = '/'.join(dest)
                        path_dest = u"%s/%s/%s" % (
                            root_path, urllib.unquote(dest), n_folder)
                        os.rename(path_src, path_dest)
                        ret['status'] = 'success'
                        ret['message'] = gettext(
                            u'Folder renamed successfully')
                        ret['data'] = u"%s/%s/" % (
                            urllib.unquote(dest), n_folder)
                    except Exception as e:
                        ret['status'] = 'error'
                        ret['message'] = e
                else:
                    ret['status'] = 'error'
                    ret['message'] = gettext(u'Invalid folder name')
            elif what == 'create':
                new_folder = request.POST.get('new_folder', '').strip()
                n_folder = clean_path(new_folder)
                if new_folder == n_folder:
                    try:
                        n_folder = urllib.unquote(n_folder)
                        rel = '%s/%s' % (urllib.unquote(path_dest), n_folder)
                        path = u"%s/%s" % (root_path, rel)
                        os.mkdir(path)
                        ret['status'] = 'success'
                        ret['message'] = gettext(
                            u'Folder created successfully')
                        ret['data'] = '<li class="directory collapsed"><a href="#" rel="%s/">%s</a></li>' % (
                            rel, n_folder)
                    except Exception as e:
                        ret['status'] = 'error'
                        ret['message'] = e
                else:
                    ret['status'] = 'error'
                    ret['message'] = gettext(u'Invalid folder name')
        else:
            ret['status'] = 'error'
            ret['message'] = gettext(u'Access denied')
    return HttpResponse(simplejson.dumps(ret))
Example #15
0
 def short_description(self):
     if self.content_type != None:
         result = self.content_type.model_class()._meta.verbose_name.lower()+': '
     else:
         result = 'None: '
     if self.inverse:
         result += gettext('not ')
     try:
         if self.object_id:
             result += smart_unicode(get_content_object(self))
         else:
             if self.content_type:
                 result += gettext('all ')+smart_unicode(self.content_type)+'s'
             else:
                 result += gettext('everything ')                    
     except AttributeError:
         pass
     
     #if result != '':
     #    result += smart_unicode(gettext(' for '))
     #if self.owner_user:
     #    result += smart_unicode(gettext('user'))+u' '+smart_unicode(self.owner_user)
     #elif self.owner_group:
     #    result += smart_unicode(gettext('group'))+u' '+smart_unicode(self.owner_group)
     #else:
     #    result += _('myself')
     
     return result
Example #16
0
def isValidQuicktimeVideoURL(field_data, all_data):
    "Checks that the given URL is a video that can be played by QuickTime (qt, mpeg)"
    uc = URLMimeTypeCheck(('video/quicktime', 'video/mpeg',))
    try:
        uc(field_data, all_data)
    except URLMimeTypeCheck.InvalidContentType:
        raise ValidationError, gettext("The URL %s does not point to a valid QuickTime video.") % field_data
def guardar_parcela(request):
    if request.POST:
        nombre_parcela=request.POST["txt_nombre"]
        codigo_parcela=request.POST["txt_codigo"]
        observacion_Parcela=request.POST["txt_observacion"]
        mensaje = None
        try:
            registrados = Parcela.objects.filter(Q(nombre = nombre_parcela) | Q(codigo = codigo_parcela))

            if registrados:
                for r in registrados:
                    if r.nombre == nombre_parcela or r.codigo == codigo_parcela:
                        if r.nombre == nombre_parcela:
                            mensaje = gettext("No se pudo actualizar esta parcela, ya existe una con el mimso nombre").decode('utf-8')

                        if r.codigo == codigo_parcela:
                            mensaje = gettext("No se pudo actualizar esta parcela, el código ingresado ya existe").decode('utf-8')

                        messages.add_message(request, messages.ERROR, gettext(mensaje).decode('utf-8'))
                        return redirect('/administrativa/parcelas/')

            empresa=Empresa.objects.all()
            parcela_guardar=Parcela(nombre=nombre_parcela, codigo=codigo_parcela, observacion=observacion_Parcela, id_propietario_id=empresa[0].id)
            parcela_guardar.save()
            messages.add_message(request, messages.SUCCESS, gettext("Parcela guardada correctamente").decode('utf-8'))
        except Exception as error:
            print(str(error), "************************************************ en parcela")
            messages.add_message(request, messages.ERROR, gettext("Error al guardar la parcela").decode('utf-8'))
    return redirect('/administrativa/parcelas/')
def convert_old_settings(app, schema_editor):
    EventSettingsStore = app.get_model('pretixbase', 'Event_SettingsStore')
    for es in EventSettingsStore.objects.filter(key='ticketoutput_pdf_layout'):
        locale_es = EventSettingsStore.objects.filter(object=es.object, key='locale').first()
        if locale_es:
            locale = locale_es.value
        else:
            locale = 'en'

        with language(locale):
            es.object.ticket_layouts.create(
                name=gettext('Default layout'),
                default=True,
                layout=es.value
            )

    for es in EventSettingsStore.objects.filter(key='ticketoutput_pdf_background'):
        locale_es = EventSettingsStore.objects.filter(object=es.object, key='locale').first()
        if locale_es:
            locale = locale_es.value
        else:
            locale = 'en'

        with language(locale):
            l = es.object.ticket_layouts.get_or_create(
                default=True,
                defaults={
                    'name': gettext('Default layout'),
                }
            )[0]

            l.background.name = es.value[7:]
            setattr(l, 'background', l.background.name)
            l.save()
            es.delete()
def guardar_nodos(request):
    if request.POST:
        nombre_nodo=request.POST["txt_nombre_nodo"]
        tipo_nodo=request.POST["txt_tipo_nodo"]
        codigo_alto=request.POST["txt_codigo_alto_nodo"]
        codigo_bajo=request.POST["txt_codigo_bajo_nodo"]
        red=request.POST["txt_red_nodo"]
        observacion=request.POST["txt_observacion_nodo"]
        id_parcela=request.POST.getlist('listParcelas')
        id_sensores=request.POST.getlist('listSensores')
        id_actuadores=request.POST.getlist('listActuadores')
        for j in id_parcela:
            dato_parcela=(int(j))
        try:
            print(nombre_nodo,'-',tipo_nodo,'-',codigo_alto,'-',codigo_bajo,'',red,'-',observacion)
            pa=Parcela.objects.get(id=str(dato_parcela))
            nodo_guardar=Nodo(nombre_nodo=nombre_nodo, tipo_nodo=tipo_nodo,
                                   codigo_alto=codigo_alto,codigo_bajo=codigo_bajo, red=red,
                                   observacion=observacion, id_parcela=pa)
            nodo_guardar.save()
            print('llllllllllllll')
            for j in id_sensores:
                guardar_nodo_sensor=Nodo_Sensor(id_nodo_id=nodo_guardar.id, id_sensor_id=(int(j)), observacion=observacion)
                guardar_nodo_sensor.save()
            for j in id_actuadores:
                guardar_nodo_actuador=Nodo_Actuador(id_actuador_id=(int(j)), id_nodo_id=nodo_guardar.id)
                guardar_nodo_actuador.save()
            messages.add_message(request, messages.SUCCESS, gettext("Nodo guardado correctamente").decode('utf-8'))
        except Exception as e:
            print(e)
            messages.add_message(request, messages.ERROR, gettext("Error al guardar nodo").decode('utf-8'))
    return redirect('/administrativa/nodos/')
Example #20
0
def film_description(context, film, words=None, edit=False):
    short = False
    if film.description:
        descr = unicode(strip_tags(film.description))
    else:
        if film.is_tv_series:
            descr = gettext("Unfortunately, this tv series does not have a description, yet.")
        else:
            descr = gettext("Unfortunately, this film does not have a description, yet.")
    if (not film.description) and film.imdb_code:
        imdb_address = "http://imdb.com/title/tt" + str(film.imdb_code) + "/"
        descr += _("\nYou can try ") + \
                "<a href=\"" + imdb_address + "\">IMDB</a>."
    if words:
        description = unicode(truncate_words(descr, words))
        short = True
    else:
        description = descr
    return {
        'film':film,
        'edit':edit,
        'can_edit': context['request'].user.is_authenticated(),
        'description':description,
        'short': short
    }
def guardar_usuario(request):
    if request.POST:
        nombre_usuario=request.POST["txt_nombre"]
        apellido_usuario=request.POST["txt_apellido"]
        username_usuario=request.POST["txt_username"]
        password_usuario=request.POST["txt_password"]
        email_usuario=request.POST["txt_email"]
        try:
            registrados = User.objects.filter(username = username_usuario)
            for r in registrados:
                if r.username == username_usuario:
                    messages.add_message(request, messages.ERROR, gettext("No se pudo ingresar el usuario, ya existe uno con el mimso nombre").decode('utf-8'))
                    return redirect('/administrativa/usuarios/')

            user_guardar=User(username=username_usuario, first_name=nombre_usuario, last_name=apellido_usuario, is_superuser=False, is_staff=False, is_active=True, email=email_usuario)
            user_guardar.set_password(password_usuario)
            user_guardar.save()
            permisos_usuario=request.POST.getlist('listPermisos')
            permisos_todos=Permiso.objects.all()
            for i in permisos_todos:
                for j in permisos_usuario:
                    if i.id == int(j):
                        menu_permiso_usuario=MenuUsuarioPermiso(id_menu_id=i.id_menu_id, id_usuario_id=user_guardar.id, id_permiso_id=j)
                        menu_permiso_usuario.save()
            messages.add_message(request, messages.SUCCESS, gettext("Usuario guardado correctamente").decode('utf-8'))
        except:
            messages.add_message(request, messages.ERROR, gettext("Error al guardar usuario").decode('utf-8'))
    return redirect('/administrativa/usuarios/')
def eliminar_usuario(request):
    variable = request.GET['dni']
    estado = request.GET['estado']
    mensaje = gettext("El usuario ha quedado inactivo").decode('utf-8')

    try:
        usuario_admin = User.objects.get(id=variable)
        if int(estado) == 0:
            usuario_admin.is_active = False
        else:
            usuario_admin.is_active = True
            mensaje = gettext("El usuario ha sido activado nuevamente").decode('utf-8')

        usuario_admin.save()

        dic = {
            'mensaje':mensaje,
            'result': 'OK'
        }
    except:
        dic = {
            'mensaje': gettext("Error al eliminar/activar el usuario").decode('utf-8'),
            'result': 'X'
        }
    data=json.dumps(dic)
    return HttpResponse(data, content_type="aplication/json")
Example #23
0
    def clean_content(self):
        content = self.cleaned_data.get('content')

        try:
            template = Template(content)

            if template.nodelist.get_nodes_by_type(IncludeNode):
                include_tag_not_allowed = ValidationError(
                    gettext('Include blocks are not allowed.'),
                    code='include_tag_not_allowed'
                )
                self.add_error('content', include_tag_not_allowed)

            if template.nodelist.get_nodes_by_type(ExtendsNode):
                extends_tag_not_allowed = ValidationError(
                    gettext('Extends blocks are not allowed.'),
                    code='extends_tag_not_allowed'
                )
                self.add_error('content', extends_tag_not_allowed)

        except TemplateSyntaxError as tse:
            template_syntax_error = ValidationError(str(tse), code='template_syntax_error')
            self.add_error('content', template_syntax_error)

        return content
Example #24
0
def create_default_ranks(apps, schema_editor):
    Rank = apps.get_model("misago_users", "Rank")

    team = Rank.objects.create(
        name=gettext("Forum team"),
        slug=slugify(gettext("Forum team")),
        title=gettext("Team"),
        css_class="primary",
        is_tab=True,
        order=0,
    )

    member = Rank.objects.create(
        name=gettext("Members"),
        slug=slugify(gettext("Members")),
        is_default=True,
        order=1,
    )

    Role = apps.get_model("misago_acl", "Role")

    team.roles.add(Role.objects.get(name=_("Moderator")))
    team.roles.add(Role.objects.get(name=_("Private threads")))
    team.roles.add(Role.objects.get(name=_("Private threads moderator")))
    team.roles.add(Role.objects.get(name=_("Deleting users")))

    member.roles.add(Role.objects.get(name=_("Private threads")))
def loggin(request):
    message = None
    if request.user.is_authenticated():
        return HttpResponseRedirect("/administrativa/")  # falta definir
    else:
        if request.method == "POST":
            vUsername = request.POST["usuario"]
            vPassword = request.POST["password"]
            user = authenticate(username=vUsername, password=vPassword)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect("/administrativa/")  # redireccionar a la pagina de inicio
                else:
                    dic = {
                        "title": gettext("Cuenta Inactiva").decode("utf-8"),
                        "notificacion": gettext(
                            "Su cuenta se encuentra inactiva comunicarse con el administrador"
                        ).decode("utf-8"),
                    }
                    return render_to_response("inicio/index.html", dic, context_instance=RequestContext(request))
            else:
                dic = {
                    "title": gettext("Datos Erróneos").decode("utf-8"),
                    "notificacion": gettext("Usuario y contraseña incorrectos").decode("utf-8"),
                }
                return render_to_response("inicio/index.html", dic, context_instance=RequestContext(request))
        return render_to_response(
            "inicio/index.html", {"notificacion": message}, context_instance=RequestContext(request)
        )
Example #26
0
    def test_check_too_much_weight(self):
        self.robot = robot = TemplateRobot()
        robot.army = self.army
        robot.chassis = Chassis.objects.all()[0]
        robot.recalculate_all_piece_and_save()
        motor = Motor.objects.all()[1]
        gene = Generator.objects.all()[2]

        r11, r12 = robot.check_for_add_piece(gene)
        self.assertEqual(r11, True)
        self.assertEqual(r12, True)

        robot.generator = gene
        robot.recalculate_all_piece_and_save()

        r1, r2 = robot.check_for_add_piece(motor)
        self.assertEqual(r1, False)
        self.assertEqual(gettext(r2), gettext(constants.TOO_MUCH_WEIGHT))

        robot.chassis = Chassis.objects.all()[2]
        robot.recalculate_all_piece_and_save()


        r11, r12 = robot.check_for_add_piece(motor)
        self.assertEqual(r11, True)
        self.assertEqual(r12, True)
Example #27
0
 def isNonEmptyFile(self, field_data, all_data):
     try:
         content = field_data['content']
     except TypeError:
         raise validators.CriticalValidationError, gettext("No file was submitted. Check the encoding type on the form.")
     if not content:
         raise validators.CriticalValidationError, gettext("The submitted file is empty.")
Example #28
0
    def clean(self, value):
        """
        Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a
        group of 14 characters.
        """
        value = super(BRCNPJField, self).clean(value)
        if value in EMPTY_VALUES:
            return u''
        orig_value = value[:]
        if not value.isdigit():
            value = re.sub("[-/\.]", "", value)
        try:
            int(value)
        except ValueError:
            raise ValidationError("This field requires only numbers.")
        if len(value) != 14:
            raise ValidationError(
                gettext("This field requires at least 14 digits"))
        orig_dv = value[-2:]

        new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(5, 1, -1) + range(9, 1, -1))])
        new_1dv = DV_maker(new_1dv % 11)
        value = value[:-2] + str(new_1dv) + value[-1]
        new_2dv = sum([i * int(value[idx]) for idx, i in enumerate(range(6, 1, -1) + range(9, 1, -1))])
        new_2dv = DV_maker(new_2dv % 11)
        value = value[:-1] + str(new_2dv)
        if value[-2:] != orig_dv:
            raise ValidationError(gettext("Invalid CNPJ number."))

        return orig_value
Example #29
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     instance = kwargs.get('instance', None)
     self.__editing_instance = False
     if instance:
         self.__editing_instance = True
         self.fields['delete_subscriptions'] = ArticleSubscriptionModelMultipleChoiceField(
             models.ArticleSubscription.objects.filter(
                 subscription__settings=instance),
             label=gettext("Remove subscriptions"),
             required=False,
             help_text=gettext("Select article subscriptions to remove from notifications"),
             initial=models.ArticleSubscription.objects.none(),
         )
         self.fields['email'] = forms.TypedChoiceField(
             label=_("Email digests"),
             choices=(
                 (0, gettext('Unchanged (selected on each article)')),
                 (1, gettext('No emails')),
                 (2, gettext('Email on any change')),
             ),
             coerce=lambda x: int(x) if x is not None else None,
             widget=forms.RadioSelect(),
             required=False,
             initial=0,
         )
Example #30
0
 def pretty_memory(self, obj):
     memory = obj.memory
     if memory is None:
         return gettext('None')
     if memory < 1000:
         return gettext('%d KB') % memory
     else:
         return gettext('%.2f MB') % (memory / 1024)
 def fromDict(cls, object_dict):
     if not object_dict.get('resourceType'):
         raise FHIRException(gettext('Missing `resourceType` attribute'))
     resource_type = object_dict.pop('resourceType')
     class_ = eval_type(resource_type)
     return class_()._fromDict(object_dict)
Example #32
0
 def __init__(self, message=None):
     self.message = message or gettext("Wrong login or password for telnet access")
Example #33
0
 def detailview_display(self, context):
     if not context['user'].has_perm('crudity'):
         raise PermissionDenied(
             gettext('Error: you are not allowed to view this block: {}'.format(self.id_))
         )
Example #34
0
def register_core_features(features):
    # Hallo.js
    features.register_editor_plugin(
        'hallo', 'hr',
        HalloPlugin(
            name='hallohr',
            js=['wagtailadmin/js/hallo-plugins/hallo-hr.js'],
            order=45,
        )
    )
    features.register_converter_rule('editorhtml', 'hr', [
        WhitelistRule('hr', allow_without_attributes)
    ])

    features.register_editor_plugin(
        'hallo', 'link',
        HalloPlugin(
            name='hallowagtaillink',
            js=[
                'wagtailadmin/js/page-chooser-modal.js',
                'wagtailadmin/js/hallo-plugins/hallo-wagtaillink.js',
            ],
        )
    )
    features.register_converter_rule('editorhtml', 'link', [
        WhitelistRule('a', attribute_rule({'href': check_url})),
        LinkTypeRule('page', PageLinkHandler),
    ])

    features.register_editor_plugin(
        'hallo', 'bold', HalloFormatPlugin(format_name='bold')
    )
    features.register_converter_rule('editorhtml', 'bold', [
        WhitelistRule('b', allow_without_attributes),
        WhitelistRule('strong', allow_without_attributes),
    ])

    features.register_editor_plugin(
        'hallo', 'italic', HalloFormatPlugin(format_name='italic')
    )
    features.register_converter_rule('editorhtml', 'italic', [
        WhitelistRule('i', allow_without_attributes),
        WhitelistRule('em', allow_without_attributes),
    ])

    headings_elements = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
    headings_order_start = HalloHeadingPlugin.default_order + 1
    for order, element in enumerate(headings_elements, start=headings_order_start):
        features.register_editor_plugin(
            'hallo', element, HalloHeadingPlugin(element=element, order=order)
        )
        features.register_converter_rule('editorhtml', element, [
            WhitelistRule(element, allow_without_attributes)
        ])

    features.register_editor_plugin(
        'hallo', 'ol', HalloListPlugin(list_type='ordered')
    )
    features.register_converter_rule('editorhtml', 'ol', [
        WhitelistRule('ol', allow_without_attributes),
        WhitelistRule('li', allow_without_attributes),
    ])

    features.register_editor_plugin(
        'hallo', 'ul', HalloListPlugin(list_type='unordered')
    )
    features.register_converter_rule('editorhtml', 'ul', [
        WhitelistRule('ul', allow_without_attributes),
        WhitelistRule('li', allow_without_attributes),
    ])

    # Draftail
    features.register_editor_plugin(
        'draftail', 'hr', draftail_features.BooleanFeature('enableHorizontalRule')
    )
    features.register_converter_rule('contentstate', 'hr', {
        'from_database_format': {
            'hr': HorizontalRuleHandler(),
        },
        'to_database_format': {
            'entity_decorators': {'HORIZONTAL_RULE': lambda props: DOM.create_element('hr')}
        }
    })

    features.register_editor_plugin(
        'draftail', 'h1', draftail_features.BlockFeature({
            'label': 'H1',
            'type': 'header-one',
            'description': gettext('Heading %(level)d') % {'level': 1},
        })
    )
    features.register_converter_rule('contentstate', 'h1', {
        'from_database_format': {
            'h1': BlockElementHandler('header-one'),
        },
        'to_database_format': {
            'block_map': {'header-one': 'h1'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'h2', draftail_features.BlockFeature({
            'label': 'H2',
            'type': 'header-two',
            'description': gettext('Heading %(level)d') % {'level': 2},
        })
    )
    features.register_converter_rule('contentstate', 'h2', {
        'from_database_format': {
            'h2': BlockElementHandler('header-two'),
        },
        'to_database_format': {
            'block_map': {'header-two': 'h2'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'h3', draftail_features.BlockFeature({
            'label': 'H3',
            'type': 'header-three',
            'description': gettext('Heading %(level)d') % {'level': 3},
        })
    )
    features.register_converter_rule('contentstate', 'h3', {
        'from_database_format': {
            'h3': BlockElementHandler('header-three'),
        },
        'to_database_format': {
            'block_map': {'header-three': 'h3'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'h4', draftail_features.BlockFeature({
            'label': 'H4',
            'type': 'header-four',
            'description': gettext('Heading %(level)d') % {'level': 4},
        })
    )
    features.register_converter_rule('contentstate', 'h4', {
        'from_database_format': {
            'h4': BlockElementHandler('header-four'),
        },
        'to_database_format': {
            'block_map': {'header-four': 'h4'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'h5', draftail_features.BlockFeature({
            'label': 'H5',
            'type': 'header-five',
            'description': gettext('Heading %(level)d') % {'level': 5},
        })
    )
    features.register_converter_rule('contentstate', 'h5', {
        'from_database_format': {
            'h5': BlockElementHandler('header-five'),
        },
        'to_database_format': {
            'block_map': {'header-five': 'h5'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'h6', draftail_features.BlockFeature({
            'label': 'H6',
            'type': 'header-six',
            'description': gettext('Heading %(level)d') % {'level': 6},
        })
    )
    features.register_converter_rule('contentstate', 'h6', {
        'from_database_format': {
            'h6': BlockElementHandler('header-six'),
        },
        'to_database_format': {
            'block_map': {'header-six': 'h6'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'ul', draftail_features.BlockFeature({
            'type': 'unordered-list-item',
            'icon': 'list-ul',
            'description': gettext('Bulleted list'),
        })
    )
    features.register_converter_rule('contentstate', 'ul', {
        'from_database_format': {
            'ul': ListElementHandler('unordered-list-item'),
            'li': ListItemElementHandler(),
        },
        'to_database_format': {
            'block_map': {'unordered-list-item': {'element': 'li', 'wrapper': 'ul'}}
        }
    })
    features.register_editor_plugin(
        'draftail', 'ol', draftail_features.BlockFeature({
            'type': 'ordered-list-item',
            'icon': 'list-ol',
            'description': gettext('Numbered list'),
        })
    )
    features.register_converter_rule('contentstate', 'ol', {
        'from_database_format': {
            'ol': ListElementHandler('ordered-list-item'),
            'li': ListItemElementHandler(),
        },
        'to_database_format': {
            'block_map': {'ordered-list-item': {'element': 'li', 'wrapper': 'ol'}}
        }
    })
    features.register_editor_plugin(
        'draftail', 'blockquote', draftail_features.BlockFeature({
            'type': 'blockquote',
            'icon': 'openquote',
            'description': gettext('Blockquote'),
        })
    )
    features.register_converter_rule('contentstate', 'blockquote', {
        'from_database_format': {
            'blockquote': BlockElementHandler('blockquote'),
        },
        'to_database_format': {
            'block_map': {'blockquote': 'blockquote'}
        }
    })

    features.register_editor_plugin(
        'draftail', 'bold', draftail_features.InlineStyleFeature({
            'type': 'BOLD',
            'icon': 'bold',
            'description': gettext('Bold'),
        })
    )
    features.register_converter_rule('contentstate', 'bold', {
        'from_database_format': {
            'b': InlineStyleElementHandler('BOLD'),
            'strong': InlineStyleElementHandler('BOLD'),
        },
        'to_database_format': {
            'style_map': {'BOLD': 'b'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'italic', draftail_features.InlineStyleFeature({
            'type': 'ITALIC',
            'icon': 'italic',
            'description': gettext('Italic'),
        })
    )
    features.register_converter_rule('contentstate', 'italic', {
        'from_database_format': {
            'i': InlineStyleElementHandler('ITALIC'),
            'em': InlineStyleElementHandler('ITALIC'),
        },
        'to_database_format': {
            'style_map': {'ITALIC': 'i'}
        }
    })

    features.register_editor_plugin(
        'draftail', 'link', draftail_features.EntityFeature({
            'type': 'LINK',
            'icon': 'link',
            'description': gettext('Link'),
            # We want to enforce constraints on which links can be pasted into rich text.
            # Keep only the attributes Wagtail needs.
            'attributes': ['url', 'id', 'parentId'],
            'whitelist': {
                # Keep pasted links with http/https protocol, and not-pasted links (href = undefined).
                'href': "^(http:|https:|undefined$)",
            }
        }, js=[
            'wagtailadmin/js/page-chooser-modal.js',
        ])
    )
    features.register_converter_rule('contentstate', 'link', {
        'from_database_format': {
            'a[href]': ExternalLinkElementHandler('LINK'),
            'a[linktype="page"]': PageLinkElementHandler('LINK'),
        },
        'to_database_format': {
            'entity_decorators': {'LINK': link_entity}
        }
    })
    features.register_editor_plugin(
        'draftail', 'superscript', draftail_features.InlineStyleFeature({
            'type': 'SUPERSCRIPT',
            'icon': 'superscript',
            'description': gettext('Superscript'),
        })
    )
    features.register_converter_rule('contentstate', 'superscript', {
        'from_database_format': {
            'sup': InlineStyleElementHandler('SUPERSCRIPT'),
        },
        'to_database_format': {
            'style_map': {'SUPERSCRIPT': 'sup'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'subscript', draftail_features.InlineStyleFeature({
            'type': 'SUBSCRIPT',
            'icon': 'subscript',
            'description': gettext('Subscript'),
        })
    )
    features.register_converter_rule('contentstate', 'subscript', {
        'from_database_format': {
            'sub': InlineStyleElementHandler('SUBSCRIPT'),
        },
        'to_database_format': {
            'style_map': {'SUBSCRIPT': 'sub'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'strikethrough', draftail_features.InlineStyleFeature({
            'type': 'STRIKETHROUGH',
            'icon': 'strikethrough',
            'description': gettext('Strikethrough'),
        })
    )
    features.register_converter_rule('contentstate', 'strikethrough', {
        'from_database_format': {
            's': InlineStyleElementHandler('STRIKETHROUGH'),
        },
        'to_database_format': {
            'style_map': {'STRIKETHROUGH': 's'}
        }
    })
    features.register_editor_plugin(
        'draftail', 'code', draftail_features.InlineStyleFeature({
            'type': 'CODE',
            'icon': 'code',
            'description': gettext('Code'),
        })
    )
    features.register_converter_rule('contentstate', 'code', {
        'from_database_format': {
            'code': InlineStyleElementHandler('CODE'),
        },
        'to_database_format': {
            'style_map': {'CODE': 'code'}
        }
    })
Example #35
0
 def name(self):
     if self.display_name:
         return force_str(self.display_name)
     else:
         return gettext('Firefox user {id}').format(id=self.id)
Example #36
0
 def __str__(self):
     if self.msgargs:
         return gettext(self.msg) % self.msgargs
     else:
         return gettext(self.msg)
Example #37
0
    def __init__(self, entity, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.report = entity
        report_ct = entity.ct
        model = report_ct.model_class()

        instance = self.instance
        fields = self.fields

        aggregate_field_f = fields['aggregate_field']
        abscissa_field_f  = fields['abscissa_field']
        is_count_f        = fields['is_count']

        get_fconf = FieldsConfig.LocalCache().get_4_model
        # TODO: split('__', 1) when 'count' is an aggregate operator
        ordinate_field_name, __, aggregate = instance.ordinate.rpartition('__')

        # Abscissa -------------------------------------------------------------
        def absc_field_excluder(field, deep):
            # TODO: set the ForeignKeys to entities as not enumerable automatically ?
            if isinstance(field, RelatedField) and \
               issubclass(field.remote_field.model, CremeEntity):
                return True

            return get_fconf(field.model).is_field_hidden(field) and \
                   field.name != instance.abscissa

        abscissa_model_fields = ModelFieldEnumerator(model, deep=0, only_leafs=False) \
                                    .filter(self._filter_abcissa_field, viewable=True) \
                                    .exclude(absc_field_excluder) \
                                    .choices()

        self.rtypes = rtypes = dict(RelationType.objects
                                                .compatible(report_ct, include_internals=True)
                                                .values_list('id', 'predicate')
                                   )
        abscissa_predicates = [*rtypes.items()]
        sort_key = collator.sort_key
        abscissa_predicates.sort(key=lambda k: sort_key(k[1]))

        abscissa_choices = [
            (_('Fields'),        abscissa_model_fields),
            (_('Relationships'), abscissa_predicates),
        ]

        self.abs_cfields = cfields = {
            cf.id: cf
                for cf in CustomField.objects
                                     .filter(field_type__in=(CustomField.ENUM,
                                                             CustomField.DATETIME,
                                                            ),
                                             content_type=report_ct,
                                            )
        }

        if cfields:
            # TODO: sort ?
            abscissa_choices.append(
                (_('Custom fields'), [(cf.id, cf.name) for cf in cfields.values()])
            )

        # TODO: we could build the complete map fields/allowed_types, instead of doing AJAX queries...
        abscissa_field_f.choices = abscissa_choices
        abscissa_field_f.widget.target_url = reverse('reports__graph_types', args=(report_ct.id,))  # Meh

        # Ordinate -------------------------------------------------------------
        def agg_field_excluder(field, deep):
            return get_fconf(field.model).is_field_hidden(field) and \
                   field.name != ordinate_field_name

        aggfields = [
            field_info[0]
                for field_info in ModelFieldEnumerator(model, deep=0)
                                    .filter((lambda f, depth: isinstance(f, field_aggregation_registry.authorized_fields)),
                                            viewable=True
                                           )
                                    .exclude(agg_field_excluder)
        ]
        aggfield_choices = [(field.name, field.verbose_name) for field in aggfields]
        aggcustom_choices = [
            *CustomField.objects
                        .filter(field_type__in=field_aggregation_registry.authorized_customfields,
                                content_type=report_ct,
                               )
                        .values_list('id', 'name')
        ]
        ordinate_choices = aggfield_choices or aggcustom_choices

        if ordinate_choices:
            self.force_count = False

            money_fields = [field for field in aggfields if isinstance(field, MoneyField)]
            if money_fields:
                # TODO: lazy lazily-translated-string interpolation
                aggregate_field_f.help_text = gettext(
                        'If you use a field related to money, the entities should use the same '
                        'currency or the result will be wrong. Concerned fields are : {}'
                    ).format(', '.join(str(field.verbose_name) for field in money_fields))

            if aggcustom_choices and aggfield_choices:
                ordinate_choices = [
                    (_('Fields'),        aggfield_choices),
                    (_('Custom fields'), aggcustom_choices),
               ]
        else:
            self.force_count = True
            ordinate_choices = [('', _('No field is usable for aggregation'))]

            disabled_attrs = {'disabled': True}
            aggregate_field_f.widget.attrs = disabled_attrs
            fields['aggregate'].widget.attrs = disabled_attrs

            is_count_f.help_text = _('You must make a count because no field is usable for aggregation')
            is_count_f.initial = True
            is_count_f.widget.attrs = disabled_attrs

        aggregate_field_f.choices = ordinate_choices

        # Initial data ---------------------------------------------------------
        data = self.data

        if data:
            get_data = data.get
            widget = abscissa_field_f.widget
            widget.source_val = get_data('abscissa_field')
            widget.target_val = get_data('abscissa_group_by')

            # NB: ugly hack ; see AbscissaGroupBySelect/toggleDaysField.
            #     Should be removed in Creme2.2 with a clean field/widget
            fields['abscissa_group_by'].widget.attrs['data-initial-value'] = get_data('abscissa_group_by')
        elif instance.pk is not None:
            fields['aggregate'].initial = aggregate
            aggregate_field_f.initial   = ordinate_field_name
            abscissa_field_f.initial    = instance.abscissa

            widget = abscissa_field_f.widget
            widget.source_val = instance.abscissa
            widget.target_val = instance.type

            # NB: idem
            fields['abscissa_group_by'].widget.attrs['data-initial-value'] = instance.type

        # TODO: remove this sh*t when is_count is a real widget well initialized (disabling set by JS)
        if is_count_f.initial or instance.is_count or data.get('is_count'):
            disabled_attrs = {'disabled': True}
            aggregate_field_f.widget.attrs = disabled_attrs
            fields['aggregate'].widget.attrs = disabled_attrs
Example #38
0
 def render(self, context):
     context[self.variable] = [(k, translation.gettext(v))
                               for k, v in settings.LANGUAGES]
     return ''
Example #39
0
def language_name_translated(lang_code):
    english_name = translation.get_language_info(lang_code)['name']
    return translation.gettext(english_name)
Example #40
0
 def __str__(self):
     return gettext('Settings')
Example #41
0
    def user_change_password(self, request, id, form_url=''):
        user = self.get_object(request, unquote(id))
        if not self.has_change_permission(request, user):
            raise PermissionDenied
        if user is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') %
                {
                    'name': self.model._meta.verbose_name,
                    'key': escape(id),
                })
        if request.method == 'POST':
            form = self.change_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                change_message = self.construct_change_message(
                    request, form, None)
                self.log_change(request, user, change_message)
                msg = gettext('Password changed successfully.')
                messages.success(request, msg)
                update_session_auth_hash(request, form.user)
                return HttpResponseRedirect(
                    reverse(
                        '%s:%s_%s_change' % (
                            self.admin_site.name,
                            user._meta.app_label,
                            user._meta.model_name,
                        ),
                        args=(user.pk, ),
                    ))
        else:
            form = self.change_password_form(user)

        fieldsets = [(None, {'fields': list(form.base_fields)})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'title':
            _('Change password: %s') % escape(user.get_username()),
            'adminForm':
            adminForm,
            'form_url':
            form_url,
            'form':
            form,
            'is_popup': (IS_POPUP_VAR in request.POST
                         or IS_POPUP_VAR in request.GET),
            'add':
            True,
            'change':
            False,
            'has_delete_permission':
            False,
            'has_change_permission':
            True,
            'has_absolute_url':
            False,
            'opts':
            self.model._meta,
            'original':
            user,
            'save_as':
            False,
            'show_save':
            True,
            **self.admin_site.each_context(request),
        }

        request.current_app = self.admin_site.name

        return TemplateResponse(
            request,
            self.change_user_password_template
            or 'admin/auth/user/change_password.html',
            context,
        )
Example #42
0
 def __str__(self):
     return gettext("Comment #%(number)d") % {"number": self.pk}
Example #43
0
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import HttpResponseForbidden
from django.shortcuts import render, get_object_or_404, redirect
from django.utils.translation import get_language, gettext
from guardian.decorators import permission_required_or_403

from common.pagination import get_page
from forms import ItemForm, ItemContentForm
from ..models import Item, ItemContent

LANGUAGES = (('ru', gettext('Russian')),
             #    ('en', gettext('English')),
             #    ('tt', gettext('Tatar')),
             )
#LANGUAGES = settings.LANGUAGES


@login_required
def index(request):
    if not request.user.has_module_perms('newinlib'):
        return HttpResponseForbidden()
    return redirect('newinlib:administration:items_list')


@login_required
@permission_required_or_403('newinlib.add_item')
def items_list(request):
Example #44
0
 def verbose_conds_use_or(self):  # TODO: templatetag instead ?
     return gettext('OR') if self.conds_use_or else gettext('AND')
Example #45
0
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")

        super().__init__(*args, **kwargs)

        self.entries = []
        for entry in CreditEntry.objects.reverse().filter(invoice__isnull=True,
                                                          notes="")[:20]:
            self.fields[f"entry_{entry.pk}_invoice"] = forms.TypedChoiceField(
                label=format_html(
                    '<a href="{}" target="_blank"'
                    ' rel="noopener noreferrer">{}, {}: {}</a>',
                    entry.get_absolute_url(),
                    entry.total,
                    local_date_format(entry.value_date),
                    entry.payment_notice,
                ),
                choices=[(None, "----------")] + [(
                    invoice.id,
                    mark_safe(" ".join((
                        format_html('<span title="{}">', invoice.description),
                        format_html(
                            "<strong>{}</strong>" if re.search(
                                r"\b" + invoice.code + r"\b",
                                entry.payment_notice,
                            ) else "{}",
                            invoice,
                        ),
                        invoice.status_badge,
                        "<br>",
                        format_html(
                            "{}",
                            invoice.contact.name_with_organization
                            if invoice.contact else invoice.customer,
                        ),
                        "<br>",
                        format_html(
                            "{} {}",
                            _("invoiced on"),
                            local_date_format(invoice.invoiced_on),
                        ) if invoice.invoiced_on else gettext("NO DATE YET"),
                        "<br>",
                        currency(invoice.total),
                        format_html(
                            "<br><span style='color:darkred'>{}: {}</span>",
                            _("third party costs"),
                            currency(invoice.third_party_costs),
                        ) if invoice.third_party_costs else "",
                        "</span>",
                    ))),
                ) for invoice in Invoice.objects.open().filter(
                    total=entry.total).select_related("contact__organization",
                                                      "customer", "owned_by",
                                                      "project")[:100]],
                coerce=int,
                required=False,
                widget=forms.RadioSelect,
            )

            self.fields[f"entry_{entry.pk}_notes"] = forms.CharField(
                widget=Textarea({"rows": 1}), label=_("notes"), required=False)

            self.entries.append((
                entry,
                f"entry_{entry.pk}_invoice",
                f"entry_{entry.pk}_notes",
            ))
Example #46
0
 def __str__(self):
     return gettext("%(name)s") % {
         "name": self.name,
     }
Example #47
0
 def format_result(self, result):
     if "'" in result["missing"]:
         result["missing"].remove("'")
         yield gettext(
             "You need to pair up an apostrophe with another one.")
     yield from super().format_result(result)
Example #48
0
 def __str__(self):
     return gettext("%(user)s: %(description)s") % {
         "user": self.user.username,
         "description": self.description,
     }
Example #49
0
def udsJs(request: 'HttpRequest') -> str:
    auth_host = request.META.get('HTTP_HOST') or request.META.get('SERVER_NAME') or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    profile = {
        'user': None if not request.user else request.user.name,
        'role': 'staff' if request.user and request.user.staff_member else 'user',
    }

    # Gets csrf token
    csrf_token = csrf.get_token(request)
    if csrf_token is not None:
        csrf_token = str(csrf_token)

    tag = request.session.get('tag', None)

    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True:
        try:
            authenticators = [Authenticator.objects.get(small_name=auth_host)]
        except Exception:
            try:
                authenticators = [Authenticator.objects.order_by('priority')[0].small_name]
            except Exception:  # There is no authenticators yet...
                authenticators = []
    else:
        authenticators = Authenticator.objects.all().exclude(visible=False)

    if tag:
        authenticators = [x for x in authenticators if x.small_name == tag]

    # the auths for client
    def getAuthInfo(auth: Authenticator):
        theType = auth.getType()
        return {
            'id': auth.uuid,
            'name': auth.name,
            'label': auth.small_name,
            'priority': auth.priority,
            'is_custom': theType.isCustom()
        }

    config = {
        'version': VERSION,
        'version_stamp': VERSION_STAMP,
        'language': get_language(),
        'available_languages': [{'id': k, 'name': gettext(v)} for k, v in settings.LANGUAGES],
        'authenticators': [getAuthInfo(auth) for auth in authenticators if auth.getType()],
        'os': request.os['OS'],
        'csrf_field': CSRF_FIELD,
        'csrf': csrf_token,
        'image_size': Image.MAX_IMAGE_SIZE,
        'experimental_features': GlobalConfig.EXPERIMENTAL_FEATURES.getBool(),
        'reload_time': GlobalConfig.RELOAD_TIME.getInt(True),
        'site_name': GlobalConfig.SITE_NAME.get(),
        'site_copyright_info': GlobalConfig.SITE_COPYRIGHT.get(),
        'site_copyright_link': GlobalConfig.SITE_COPYRIGHT_LINK.get(),
        'messages': {
            # Calendar denied message
            'calendarDenied': GlobalConfig.LIMITED_BY_CALENDAR_TEXT.get().strip() or gettext('Access limited by calendar')
        },
        'urls': {
            'changeLang': reverse('set_language'),
            'login': reverse('page.login'),
            'logout': reverse('page.logout'),
            'user': reverse('page.index'),
            'customAuth': reverse('uds.web.views.customAuth', kwargs={'idAuth': ''}),
            'services': reverse('webapi.services'),
            'enabler': reverse('webapi.enabler', kwargs={'idService': 'param1', 'idTransport': 'param2'}),
            'action': reverse('webapi.action', kwargs={'idService': 'param1', 'actionString': 'param2'}),
            'galleryImage': reverse('webapi.galleryImage', kwargs={'idImage': 'param1'}),
            'transportIcon': reverse('webapi.transportIcon', kwargs={'idTrans': 'param1'}),
            'static': static(''),
            # Launcher URL if exists
            'launch': request.session.get('launch', ''),
        }
    }

    # all plugins are under url clients...
    plugins = [
        {
            'url': static('clients/' + url.format(version=CLIENT_VERSION)),
            'description': description,
            'name': name
        } for url, description, name in (
            ('UDSClientSetup-{version}.exe', gettext('Windows client'), 'Windows'),
            ('UDSClient-{version}.pkg', gettext('Mac OS X client'), 'MacOS'),
            ('udsclient_{version}_all.deb', gettext('Debian based Linux client') + ' ' + gettext('(requires Python-2.7)'), 'Linux'),
            ('udsclient-{version}-1.noarch.rpm', gettext('Red Hat based Linux client (RH, Fedora, Centos, ...)') + ' ' + gettext('(requires Python-2.7)'), 'Linux'),
            ('udsclient-opensuse-{version}-1.noarch.rpm', gettext('Suse based Linux client') + ' ' + gettext('(requires Python-2.7)'), 'Linux'),
            ('udsclient-{version}.tar.gz', gettext('Generic .tar.gz Linux client') + ' ' + gettext('(requires Python-2.7)'), 'Linux')
        )
    ]

    actors: typing.List[typing.Dict[str, str]] = []

    if profile['role'] == 'staff':  # Add staff things
        # If is admin (informational, REST api checks users privileges anyway...)
        profile['admin'] = True
        # REST auth
        config['auth_token'] = request.session.session_key
        config['auth_header'] = AUTH_TOKEN_HEADER
        # Actors
        actors = [{'url': reverse('utility.downloader', kwargs={'idDownload': key}), 'name': val['name'], 'description': gettext(val['comment'])} for key, val in downloadsManager().getDownloadables().items()]
        # URLS
        config['urls']['admin'] = reverse('uds.admin.views.index')
        config['urls']['rest'] = reverse('REST', kwargs={'arguments': ''})

    errors: typing.List = []
    if 'errors' in request.session:
        errors = request.session['errors']
        del request.session['errors']
        request.session.modified = True  # Ensure saves it

    uds = {
        'profile': profile,
        'config': config,
        'plugins': plugins,
        'actors': actors,
        'errors': errors,
        'data': request.session.get('data')
    }

    # Reset some 1 time values...
    request.session['launch'] = ''

    return 'var udsData = ' + json.dumps(uds) + ';\n'
Example #50
0
    def form_valid(self, form):
        self.object = form.save()

        # Fetch all products
        basket = self.request.session.get('basket', [])
        products_in_basket = [item.get('product') for item in basket]
        products = Product.objects.filter(pk__in=products_in_basket,
                                          active=True,
                                          shop__active=True).order_by('shop')
        products_dict = {product.pk: product for product in products}

        # Total cost & valid items list per shop
        shop_items_and_cost = dict.fromkeys(
            {product.shop
             for product in products})
        for key in shop_items_and_cost:
            shop_items_and_cost[key] = {
                'total_cost': Decimal(0.00),
                'order_items': [],
                'item_count': 0
            }

        # Create orderItems
        for item in basket:
            product = products_dict[item.get('product')]
            count = item.get('count')
            # If product is not found, skip product
            if product is None:
                continue

            # If count is 0 or below, skip item
            if count < 1:
                continue

            order_item = OrderItem()
            order_item.product = product
            order_item.order = self.object
            order_item.count = count
            # Save the offer/on sale price if any, else use normal price
            order_item.price = product.offer_price if product.offer_price else product.price
            order_item.save()

            shop_items_and_cost[product.shop]['item_count'] += count
            shop_items_and_cost[product.shop]['total_cost'] += Decimal(
                order_item.subtotal())
            shop_items_and_cost[product.shop]['order_items'].append(order_item)

        context = {
            'order': self.object,
            'shop_items_and_cost': shop_items_and_cost
        }
        html_message = render_to_string('emails/order_confirmation.html',
                                        context)
        txt_message = render_to_string('emails/order_confirmation.txt',
                                       context)
        subject = gettext('Order confirmation')

        self.object.status = Order.ORDERED

        email = EmailMultiAlternatives(subject, txt_message)
        email.from_email = settings.DEFAULT_FROM_EMAIL
        email.to = [self.object.email]
        email.attach_alternative(html_message, "text/html")
        email.content_subtype = 'html'
        email.mixed_subtype = 'related'

        with open('base/static/base/img/fb_logo.png', mode='rb') as f:
            image = MIMEImage(f.read())
            image.add_header('Content-ID', "<Foodbee_logo_long.png>")
            email.attach(image)

        email.send()

        # Clear session
        self.request.session.flush()
        return HttpResponseRedirect(self.get_success_url())
Example #51
0
 def clean(self):
     if self.is_user_id and not self.first_name:
         raise ValidationError(
             gettext(
                 'This Contact is related to a user and must have a first name.'
             ))
Example #52
0
 def show_public(self, obj):
     return format_html('<a href="{1}">{0}</a>', gettext('View on site'),
                        obj.get_absolute_url())
Example #53
0
 def last_execution(self, obj):
     return format_html(
         '{0} <a href="{1}?command__name__exact={2}" title="{3}">({3})</a>',
         localize(obj.last_execution),
         reverse('admin:command_scheduler_log_changelist'), obj.name,
         gettext('Logs'))
Example #54
0
def action_message_to_list(action: LogEntry) -> List[Dict]:
    """
    Retrieves a formatted list with all actions taken by a user given a log entry object
    """
    messages = []

    def added(x: str) -> Dict:
        return {
            "msg": x,
            "icon": "plus-circle",
            "colour": "success",
        }

    def changed(x: str) -> Dict:
        return {
            "msg": x,
            "icon": "edit",
            "colour": "blue",
        }

    def deleted(x: str) -> Dict:
        return {
            "msg": x,
            "icon": "trash",
            "colour": "danger",
        }

    if action.change_message and action.change_message[0] == "[":
        try:
            change_message = json.loads(action.change_message)
        except json.JSONDecodeError:
            return [action.change_message]

        for sub_message in change_message:
            if "added" in sub_message:
                if sub_message["added"]:
                    sub_message["added"]["name"] = gettext(
                        sub_message["added"]["name"])
                    messages.append(
                        added(
                            gettext("Added {name} “{object}”.").format(
                                **sub_message["added"])))
                else:
                    messages.append(added(gettext("Added.")))

            elif "changed" in sub_message:
                sub_message["changed"]["fields"] = get_text_list(
                    [
                        gettext(field_name)
                        for field_name in sub_message["changed"]["fields"]
                    ],
                    gettext("and"),
                )
                if "name" in sub_message["changed"]:
                    sub_message["changed"]["name"] = gettext(
                        sub_message["changed"]["name"])
                    messages.append(
                        changed(
                            gettext("Changed {fields}.").format(
                                **sub_message["changed"])))
                else:
                    messages.append(
                        changed(
                            gettext("Changed {fields}.").format(
                                **sub_message["changed"])))

            elif "deleted" in sub_message:
                sub_message["deleted"]["name"] = gettext(
                    sub_message["deleted"]["name"])
                messages.append(
                    deleted(
                        gettext("Deleted “{object}”.").format(
                            **sub_message["deleted"])))

    return messages if len(messages) else [
        changed(gettext(action.change_message))
    ]
Example #55
0
class LoadEmailMarketingOptOutsForm(forms.Form):
    """Form used for loading a CSV file to opt out contacts from email marketing."""

    HEADER_DECODE_ERROR_MESSAGE = gettext(
        'There was an error decoding the file contents.')
    BODY_DECODE_ERROR_MESSAGE = gettext(
        'There was an error decoding the text in the file provided. No records have been '
        'modified.', )
    NO_EMAIL_COLUMN_MESSAGE = gettext(
        'This file does not contain an email column.')

    email_list = forms.FileField(
        label='Email list (CSV file)',
        validators=[FileExtensionValidator(allowed_extensions=('csv', ))],
    )

    def clean_email_list(self):
        """Validates the uploaded CSV file and creates a CSV DictReader from it."""
        # This could be an instance of InMemoryUploadedFile or TemporaryUploadedFile
        # (depending on the file size)
        file_field = self.cleaned_data['email_list']

        # Guess the file encoding (primarily to check for a UTF-8 BOM)
        encoding_detector = UniversalDetector()
        for chunk in file_field.chunks():
            encoding_detector.feed(chunk)
            if encoding_detector.done:
                break

        detection_result = encoding_detector.close()
        encoding = detection_result['encoding']

        file_field.seek(0)
        csv_reader = csv.DictReader(
            io.TextIOWrapper(file_field, encoding=encoding))

        self._validate_columns(csv_reader)
        return csv_reader

    def save(self, user):
        """
        Persists the data to the database.

        :raises ValidationError: Occurs if there is a problem while reading the data from the
                                 CSV file.
        """
        try:
            return self._save(user)
        except UnicodeError:
            # This will only be triggered for invalid Unicode that is relatively deep in the file,
            # as invalid Unicode near the beginning of the file will be picked up by
            # clean_email_list().
            raise ValidationError(self.BODY_DECODE_ERROR_MESSAGE,
                                  code='body-unicode-error')

    save.alters_data = True

    @classmethod
    def _validate_columns(cls, csv_reader):
        try:
            fieldnames = csv_reader.fieldnames
        except UnicodeError as exc:
            raise ValidationError(
                cls.HEADER_DECODE_ERROR_MESSAGE,
                code='header-unicode-error',
            ) from exc

        if 'email' not in fieldnames:
            raise ValidationError(cls.NO_EMAIL_COLUMN_MESSAGE,
                                  code='no-email-column')

    @reversion.create_revision()
    @disable_search_signal_receivers(Contact)
    def _save(self, user):
        reversion.set_user(user)
        reversion.set_comment('Loaded bulk email opt-out list.')

        num_contacts_matched = 0
        num_contacts_updated = 0
        num_non_matching_email_addresses = 0

        for row in self.cleaned_data['email_list']:
            email = row['email'].strip()

            if not email:
                continue

            contacts = Contact.objects.filter(email__iexact=email)

            for contact in contacts:
                num_contacts_matched += 1

                if contact.accepts_dit_email_marketing:
                    num_contacts_updated += 1
                    contact.accepts_dit_email_marketing = False
                    contact.modified_by = user
                    contact.save()

            if not contacts:
                logger.warning(
                    f'Could not find a contact with email address {email}')
                num_non_matching_email_addresses += 1

        return _ProcessOptOutResult(
            num_contacts_matched,
            num_contacts_updated,
            num_non_matching_email_addresses,
        )
# -*- coding: utf-8 -*-
from django.utils.translation import gettext

gettext("""Mobile""")
Example #57
0
def set_up_new_course(request):
    # type: (http.HttpRequest) -> http.HttpResponse
    if request.method == "POST":
        form = CourseCreationForm(request.POST)

        if form.is_valid():
            new_course = form.save(commit=False)

            from course.content import get_course_repo_path
            repo_path = get_course_repo_path(new_course)

            try:
                import os
                os.makedirs(repo_path)

                repo = None

                try:
                    with transaction.atomic():
                        repo = Repo.init(repo_path)

                        client, remote_path = \
                            get_dulwich_client_and_remote_path_from_course(
                                    new_course)

                        fetch_pack_result = client.fetch(remote_path, repo)
                        if not fetch_pack_result.refs:
                            raise RuntimeError(
                                _("No refs found in remote repository"
                                  " (i.e. no master branch, no HEAD). "
                                  "This looks very much like a blank repository. "
                                  "Please create course.yml in the remote "
                                  "repository before creating your course."))

                        transfer_remote_refs(repo, fetch_pack_result)
                        new_sha = repo[b"HEAD"] = fetch_pack_result.refs[
                            b"HEAD"]

                        vrepo = repo
                        if new_course.course_root_path:
                            from course.content import SubdirRepoWrapper
                            vrepo = SubdirRepoWrapper(
                                vrepo, new_course.course_root_path)

                        from course.validation import validate_course_content
                        validate_course_content(  # type: ignore
                            vrepo, new_course.course_file,
                            new_course.events_file, new_sha)

                        del vrepo

                        new_course.active_git_commit_sha = new_sha.decode()
                        new_course.save()

                        # {{{ set up a participation for the course creator

                        part = Participation()
                        part.user = request.user
                        part.course = new_course
                        part.status = participation_status.active
                        part.save()

                        part.roles.set([
                            # created by signal handler for course creation
                            ParticipationRole.objects.get(
                                course=new_course, identifier="instructor")
                        ])

                        # }}}

                        messages.add_message(
                            request, messages.INFO,
                            _("Course content validated, creation "
                              "succeeded."))
                except Exception as e:
                    # Don't coalesce this handler with the one below. We only want
                    # to delete the directory if we created it. Trust me.

                    # Make sure files opened for 'repo' above are actually closed.
                    if repo is not None:  # noqa
                        repo.close()  # noqa

                    from relate.utils import force_remove_path

                    try:
                        force_remove_path(repo_path)
                    except OSError:
                        messages.add_message(
                            request, messages.WARNING,
                            gettext("Failed to delete unused "
                                    "repository directory '%s'.") % repo_path)

                    # We don't raise the OSError thrown by force_remove_path
                    # This is to ensure correct error msg for PY2.
                    raise e

                else:
                    assert repo is not None
                    repo.close()

            except Exception as e:
                from traceback import print_exc
                print_exc()

                messages.add_message(
                    request, messages.ERROR,
                    string_concat(_("Course creation failed"),
                                  ": %(err_type)s: %(err_str)s") % {
                                      "err_type": type(e).__name__,
                                      "err_str": str(e)
                                  })
            else:
                return redirect("relate-course_page", new_course.identifier)

    else:
        form = CourseCreationForm()

    return render(request, "generic-form.html", {
        "form_description": _("Set up new course"),
        "form": form
    })
Example #58
0
def update_course(pctx):
    if not (pctx.has_permission(pperm.update_content)
            or pctx.has_permission(pperm.preview_content)):
        raise PermissionDenied()

    course = pctx.course
    request = pctx.request
    content_repo = pctx.repo

    from course.content import SubdirRepoWrapper
    if isinstance(content_repo, SubdirRepoWrapper):
        repo = content_repo.repo
    else:
        repo = content_repo

    participation = pctx.participation

    previewing = bool(participation is not None
                      and participation.preview_git_commit_sha)

    may_update = pctx.has_permission(pperm.update_content)

    response_form = None
    form = None
    if request.method == "POST":
        form = GitUpdateForm(may_update, previewing, repo, request.POST,
                             request.FILES)

        command = None
        for cmd in ALLOWED_COURSE_REVISIOIN_COMMANDS:
            if cmd in form.data:
                command = cmd
                break

        if command is None:
            raise SuspiciousOperation(_("invalid command"))

        if form.is_valid():
            new_sha = form.cleaned_data["new_sha"].encode()

            try:
                run_course_update_command(
                    request,
                    repo,
                    content_repo,
                    pctx,
                    command,
                    new_sha,
                    may_update,
                    prevent_discarding_revisions=form.
                    cleaned_data["prevent_discarding_revisions"])
            except Exception as e:
                import traceback
                traceback.print_exc()

                messages.add_message(
                    pctx.request, messages.ERROR,
                    string_concat(
                        pgettext("Starting of Error message", "Error"),
                        ": %(err_type)s %(err_str)s") % {
                            "err_type": type(e).__name__,
                            "err_str": str(e)
                        })
        else:
            response_form = form

    if response_form is None:
        previewing = bool(participation is not None
                          and participation.preview_git_commit_sha)

        form = GitUpdateForm(
            may_update, previewing, repo, {
                "new_sha": repo.head().decode(),
                "prevent_discarding_revisions": True,
            })

    from django.template.loader import render_to_string
    form_text = render_to_string(
        "course/git-sha-table.html", {
            "participation":
            participation,
            "is_previewing":
            previewing,
            "course":
            course,
            "repo":
            repo,
            "current_git_head":
            repo.head().decode(),
            "git_url":
            request.build_absolute_uri(
                reverse("relate-git_endpoint", args=(course.identifier, ""))),
            "token_url":
            reverse("relate-manage_authentication_tokens",
                    args=(course.identifier, )),
        })

    assert form is not None

    return render_course_page(
        pctx, "course/generic-course-form.html", {
            "form": form,
            "form_text": form_text,
            "form_description": gettext("Update Course Revision"),
        })
Example #59
0
 def get_object(self, queryset=None):
     pk = self.request.GET.get('pk')
     if pk is None:
         raise Http404(gettext('Please specify the pk!'))
     self.kwargs.update({'pk': self.request.GET.get('pk')})
     return super().get_object(queryset=queryset)
Example #60
0
def create_stellar_deposit(transaction: Transaction,
                           destination_exists: bool = False) -> bool:
    """
    Create and submit the Stellar transaction for the deposit.

    The Transaction can be either `pending_anchor` if the task is called
    from `poll_pending_deposits()` or `pending_trust` if called from the
    `check_trustlines()`.
    """
    if transaction.status not in [
            Transaction.STATUS.pending_anchor,
            Transaction.STATUS.pending_trust,
    ]:
        raise ValueError(
            f"unexpected transaction status {transaction.status} for "
            "create_stellar_deposit", )
    elif transaction.amount_in is None or transaction.amount_fee is None:
        transaction.status = Transaction.STATUS.error
        transaction.status_message = (
            "`amount_in` and `amount_fee` must be populated, skipping transaction"
        )
        transaction.save()
        raise ValueError(transaction.status_message)

    # if we don't know if the destination account exists
    if not destination_exists:
        try:
            _, created, pending_trust = get_or_create_transaction_destination_account(
                transaction)
        except RuntimeError as e:
            transaction.status = Transaction.STATUS.error
            transaction.status_message = str(e)
            transaction.save()
            logger.error(transaction.status_message)
            return False
        if created or pending_trust:
            # the account is pending_trust for the asset to be received
            if pending_trust and transaction.status != Transaction.STATUS.pending_trust:
                transaction.status = Transaction.STATUS.pending_trust
                transaction.save()
            return False

    # if the distribution account's master signer's weight is great or equal to the its
    # medium threshold, verify the transaction is signed by it's channel account
    master_signer = None
    if transaction.asset.distribution_account_master_signer:
        master_signer = json.loads(
            transaction.asset.distribution_account_master_signer)
    thresholds = json.loads(transaction.asset.distribution_account_thresholds)
    if not (master_signer
            and master_signer["weight"] >= thresholds["med_threshold"]):
        multisig = True
        envelope = TransactionEnvelope.from_xdr(
            transaction.envelope_xdr, settings.STELLAR_NETWORK_PASSPHRASE)
        try:
            _verify_te_signed_by_account_id(envelope,
                                            transaction.channel_account)
        except InvalidSep10ChallengeError:
            transaction.status = Transaction.STATUS.error
            transaction.status_message = gettext(
                "Multisig transaction's envelope was not signed by channel account"
            )
            transaction.save()
            return False
    # otherwise, create the envelope and sign it with the distribution account's secret
    else:
        multisig = False
        distribution_acc, _ = get_account_obj(
            Keypair.from_public_key(transaction.asset.distribution_account))
        envelope = create_transaction_envelope(transaction, distribution_acc)
        envelope.sign(transaction.asset.distribution_seed)
        transaction.envelope_xdr = envelope.to_xdr()

    try:
        return submit_stellar_deposit(transaction, multisig=multisig)
    except RuntimeError as e:
        transaction.status_message = str(e)
        transaction.status = Transaction.STATUS.error
        transaction.save()
        logger.error(transaction.status_message)
        return False