Exemplo n.º 1
0
    def test_translated(self):
        self.assertEqual('{"a": "b"}', json.dumps({'a': _l('b')}, cls=LazyEncoder))

        # these are just here to improve branch coverage :-)
        self.assertEqual('{"a": "b"}', json.dumps({'a': _('b')}, cls=LazyEncoder))
        self.assertEqual('{"a": "2016-03-26T00:00:00"}',
                         json.dumps({'a': datetime(2016, 3, 26)}, cls=LazyEncoder))
Exemplo n.º 2
0
    def getIdpsByCategory(self, lang=None, exclude=None):
        """Returns a sequence of tuples of the form:

        (category, [ idp1, idp2, ...])

        where idpX is a dict { 'name': name, 'id': entityid }

        The list of idps is sorted by name

        """
        if not lang:
            lang = get_language()

        if exclude:
            validcats = filter(lambda x: x[0] not in exclude, institution_categories)
        else:
            validcats = institution_categories

        cats = map(lambda x: x[0], validcats)

        categories = map(lambda x: {'id': x[0], 'name': _l(x[1])}, validcats)

        idps = []

        # if no valid categories are found, return all idp's
        if not validcats:
            catidps = self.getEntities()
            return [('institutions', catidps)]

        for category in cats:
            catidps = sorted(self.getCategoryIdps(category))
            idps.append(map(lambda x: {'name': x.getName(lang), 'url': x.getURL(lang), 'id': x.id}, catidps))

        return zip(categories, idps)
Exemplo n.º 3
0
 def data_sharing(self, obj):
     dsp = obj.get_data_sharing_page()
     if dsp:
         pvr = PageViewRestriction.objects.filter(page=dsp).first()
         if pvr:
             return pvr.password
         else:
             return None
     else:
         return mark_safe('<em>{}</em>'.format(_l('No data sharing')))
Exemplo n.º 4
0
class SskExternalAttendee(CourseAttendee, AbstractCertificateInformationMixin,
                          InvoiceMixin):
    class Meta:
        verbose_name = _l(
            'External participant for course with official certificate')

    identifier = 'sskexternal'
    display_name = _l('External')
    display_name_plural = _l('Externals')
    additional_admin_fields = (
        ('invoice_company', _('company')),
        ('payed', _('has payed')),
    )
    forms = [
        'courses.forms.SskExternalDataForm',
        'courses.forms.SskExternalAttendeeCertificateForm',
        'courses.forms.SskExternalAttendeInvoiceForm',
        'courses.forms.SskExternalAttendeeTermsAndConditionsForm'
    ]
Exemplo n.º 5
0
class AssignedQCDetailsFilter(UnitTestCollectionFilter):

    refs_tols = django_filters.filters.ChoiceFilter(
        label=_l("References & Tolerances"),
        choices=[
            ("both", _l("Both")),
            ("refs_tols_set", _l("Only Tests with Refs/Tols")),
            ("refs_tols_not_set", _l("Only Tests without Refs/Tols")),
        ],
        required=True,
        initial="both",
        help_text=_l(
            "Select whether you want to include tests with a Reference or Tolerance Set, Not Set, or Both"
        ),
    )

    class Meta:
        model = models.UnitTestCollection
        fields = ["unit__site", "unit", "frequency", "assigned_to", "active"]
Exemplo n.º 6
0
class CommonSettingsForm(SettingsForm):
    """ Configures common or generic settings that don't belong elsewhere. """
    pipelines_disabled = forms.BooleanField(required=False,
        label=_l("Pipelines are disabled upon creation?"))
    recover_request_notification_url = forms.URLField(required=False,
        label=_('Recovery request: URL to notify'))
    recover_request_notification_auth_username = forms.CharField(required=False,
        label=_('Recovery request notification: Username (optional)'))
    recover_request_notification_auth_password = forms.CharField(required=False,
        label=_('Recovery request notification: Password (optional)'))
Exemplo n.º 7
0
class Quarto(models.Model):

    class Meta:
        verbose_name = _l('Quarto')
        verbose_name_plural = _l('Quartos')

    def __str__(self):
        return str(self.numero)

    numero = models.IntegerField(
        verbose_name=_l('Número do quarto'),
        validators=[MinValueValidator(1)]
    )

    status = models.ForeignKey(
        StatusQuarto,
        verbose_name=_l('Situação do quarto'),
        on_delete=models.PROTECT
    )
Exemplo n.º 8
0
class Supplier(models.Model):

    name = models.CharField(
        verbose_name=_l("supplier"),
        max_length=32,
        unique=True,
        help_text=_l("Enter a unique name for this supplier"),
    )
    address = models.TextField(
        verbose_name=_l("address"),
        blank=True,
    )
    phone_number = models.CharField(
        verbose_name=_l("phone number"),
        blank=True,
        max_length=31,
        help_text=_l("Company phone number"),
    )
    website = models.URLField(
        verbose_name=_l("website"),
        blank=True,
        help_text=_l("Enter a URL for the company"),
    )
    notes = models.TextField(
        verbose_name=_l("notes"),
        max_length=255,
        blank=True,
        null=True,
        help_text=_l('Additional comments about this supplier'),
    )

    class Meta:
        ordering = ('name', )

    def get_absolute_url(self):
        return reverse("supplier_details", kwargs={"pk": self.pk})

    def get_website_tag(self):
        if self.website:
            return format_html('<a href="%s" title="%s">%s</a>' % (
                self.website,
                _("Click to visit this suppliers website"),
                self.website,
            ))
        return ""

    def __str__(self):
        return self.name
Exemplo n.º 9
0
    def test_translated(self):
        self.assertEqual('{"a": "b"}',
                         json.dumps({'a': _l('b')}, cls=LazyEncoder))

        # these are just here to improve branch coverage :-)
        self.assertEqual('{"a": "b"}',
                         json.dumps({'a': _('b')}, cls=LazyEncoder))
        self.assertEqual(
            '{"a": "2016-03-26T00:00:00"}',
            json.dumps({'a': datetime(2016, 3, 26)}, cls=LazyEncoder))
Exemplo n.º 10
0
class Event(models.Model):
    """ Stores requests to modify packages that need admin approval.

    Eg. delete AIP can be requested by a pipeline, but needs storage
    administrator approval.  Who made the request and why is also stored. """
    package = models.ForeignKey('Package', to_field='uuid')
    DELETE = 'DELETE'
    RECOVER = 'RECOVER'
    EVENT_TYPE_CHOICES = (
        (DELETE, _l('delete')),
        (RECOVER, _l('recover')),
    )
    event_type = models.CharField(max_length=8, choices=EVENT_TYPE_CHOICES)
    event_reason = models.TextField()
    pipeline = models.ForeignKey('Pipeline', to_field='uuid')
    user_id = models.PositiveIntegerField()
    user_email = models.EmailField(max_length=254)
    SUBMITTED = 'SUBMIT'
    APPROVED = 'APPROVE'
    REJECTED = 'REJECT'
    EVENT_STATUS_CHOICES = (
        (SUBMITTED, _l('Submitted')),
        (APPROVED, _l('Approved')),
        (REJECTED, _l('Rejected')),
    )
    status = models.CharField(max_length=8, choices=EVENT_STATUS_CHOICES)
    status_reason = models.TextField(null=True, blank=True)
    admin_id = models.ForeignKey(settings.AUTH_USER_MODEL,
                                 null=True,
                                 blank=True)
    status_time = models.DateTimeField(auto_now=True)
    store_data = models.TextField(null=True, blank=True, editable=False)

    class Meta:
        verbose_name = _l("Event")
        app_label = 'locations'

    def __unicode__(self):
        return _(u"%(event_status)s request to %(event_type)s %(package)s") % {
            'event_status': self.get_status_display(),
            'event_type': self.get_event_type_display(),
            'package': self.package
        }
Exemplo n.º 11
0
class ProjectModelAdmin(ModelAdmin):
    model = Project
    menu_label = _l('Projects')
    menu_icon = ' icon-fa-calendar'
    list_display = ('title', 'active_since', 'expires_at', 'workgroup',
                    'public')
    index_view_extra_js = ['js/admin/fix_admin_headers.js']
    menu_order = 400
    exclude_from_explorer = False
    list_filter = (ProjectExpiredFilter, )
    button_helper_class = ProjectButtonHelper
    inspect_view_enabled = True
    inspect_view_class = ProjectInspectView
    inspect_template_name = 'userinput/admin/inspect_project.html'

    def active_since(self, obj):
        return obj.go_live_at

    active_since.short_description = _l('active since')

    def expires_at(self, obj):
        return obj.expire_at

    expires_at.short_description = _l('Will expire at')

    def workgroup(self, obj):
        try:
            return "{}: {}".format(obj.get_workgroup().get_head().full_name(),
                                   obj.get_workgroup_info())
        except:
            return "{}".format(
                #                obj.get_workgroup().get_head().full_name(),
                obj.get_workgroup_info())

    workgroup.short_description = _l('Workgroup')

    def public(self, obj):
        if obj.is_confidential:
            return _l("No")
        else:
            return _l("Yes")

    public.short_description = _l('public')
Exemplo n.º 12
0
class SskStudentAttendee ( 
        AbstractStudentAttendee, AbstractCertificateInformationMixin
):
    class Meta:
        verbose_name = _l( 'student for course with official certificate' )

    identifier = 'sskstudent'
    display_name =_l('Student')
    display_name_plural =_l('Students')
    forms = [
        'courses.forms.RUBIDForm', 
        'courses.forms.SskStudentForm', 
        'courses.forms.SskStudentCertificateForm', 
        'courses.forms.SskStudentTermsAndConditionsForm'
    ]
    
    additional_admin_fields = (
        ('student_course', _('student course')),
    )
Exemplo n.º 13
0
    def clean_cep(self):
        """
            Remove a máscara do campo
        """
        cep = self.cleaned_data.get('cep')

        if cep:
            return cep.replace("-", "")

        raise ValidationError(
            _l('O campo de CEP é de preenchimento obrigatório.'))
Exemplo n.º 14
0
class NotificationRelatedObject(BaseModel):
    """
    Represents named object related to a notification. This object can be then referenced in notification template
    fields.

    Attributes:
        name: String identificator of the object (for referencing in templates).
        notification: Related notification.
        content_object: The related object itself.
    """
    name = models.CharField(max_length=200, verbose_name=_l('name'))
    notification = models.ForeignKey(
        Notification,
        on_delete=models.CASCADE,
        related_name='related_objects',
        verbose_name=_l('notification'),
    )
    content_type = models.ForeignKey(ContentType, null=True, on_delete=models.SET_NULL, verbose_name=_l('content type'))
    object_id = models.TextField(db_index=True, verbose_name=_l('object ID'))
    content_object = GenericForeignKey('content_type', 'object_id')
Exemplo n.º 15
0
class SingleButtonMixin(object):
    action_text = _l('Save')

    def __init__(self, *args, **kwargs):
        super(SingleButtonMixin, self).__init__(*args, **kwargs)
        self.helper = getattr(self, 'helper', FormHelper(self))
        self.helper.layout.append(
            FormActions(
                Submit('action', self.action_text, css_class="btn-primary"),
            )
        )
Exemplo n.º 16
0
class IDCardNoValidator(object):
    """
    Czech id card number field validator.
    """
    error_messages = {
        'invalid_format': _l('Enter an ID card in the format XXXXXXXXX.'),
        'invalid': _l('Enter a valid ID card number.'),
    }
    ID_CARD_NUMBER = re.compile(r'^\d{9}$')

    def __call__(self, value):
        value = force_text(value)

        match = re.match(self.ID_CARD_NUMBER, value)
        if not match:
            raise ValidationError(self.error_messages[INVALID_FORMAT], code=INVALID_FORMAT)
        elif value[0] == '0':
            raise ValidationError(self.error_messages[INVALID], code=INVALID)
        else:
            return value
Exemplo n.º 17
0
class CustomLoginForm(SingleButtonMixin, LoginForm):
    action_text = _l('Sign In')

    def __init__(self, *args, **kwargs):
        super(CustomLoginForm, self).__init__(*args, **kwargs)
        self.fields['login'].label = _('Login')
        self.helper.form_class = 'login-form'
        self.helper.layout = Layout(
            PrependedText('login', '<i class="fa fa-user"></i>'),
            PrependedText('password', '<i class="fa fa-key"></i>', type='password')
        )
Exemplo n.º 18
0
class PasswordResetSuccessView(View):
    breadcrumb = _l("")

    def get(self, request):
        # TODO unfortunately the extra_context is omitted and not provided
        return password_reset_done(request,
                                   'registration/password_reset_done.html')

    def post(self, request):
        return password_reset_done(request,
                                   'registration/password_reset_done.html')
Exemplo n.º 19
0
class SEScheduleSiteFilter(q_admin.SiteFilter):

    title = _l('Site')
    parameter_name = "sitefilter"

    def queryset(self, request, queryset):

        if self.value():
            return queryset.filter(unit_service_area__unit__site=self.value())

        return queryset
Exemplo n.º 20
0
class PublicationsMA(ModelAdmin):
    model = PublicationSnippet
    list_display = ('_title', 'year', 'journal', 'ag')

    def _title(self, obj):
        if obj.doi:

            return mark_safe(
                '<a href="https://doi.org/{doi}" target="_new">{title}</a>'.
                format(doi=obj.doi, title=obj.title))
        return obj.title

    _title.short_description = _l('title')
    _title.admin_order_field = 'title'

    def ag(self, obj):
        return mark_safe(
            get_project_and_group(Project2PublicationRelation, obj))

    ag.short_description = format_lazy('{}/{}', _l('Project'), _l('workgroup'))
Exemplo n.º 21
0
class CourseInformationPageModelAdmin(ModelAdmin):
    model = CourseInformationPage
    menu_label = _l('courses')
    menu_icon = 'fa-calendar'
    exclude_from_explorer = True
    list_display = ('_title', )

    def _title(self, obj):
        return obj.title_trans

    _title.short_description = _('Title')
Exemplo n.º 22
0
class SuccessView(LoginRequiredMixin, View):
    breadcrumb = _l("")

    def get(self, request):
        try:
            invite_list = request.session['invite_list']
            request.session.pop('invite_list', None)
            request.session.modified = True
        except:
            invite_list = []
        return render(request, 'invite_users/successfully_invited.html', {'invite_list': invite_list})
Exemplo n.º 23
0
class ProjectDetailTimelogView(LoginRequiredMixin, UserPassesTestMixin,
                               TemplateView):
    template_name = 'project/project_timelog.html'
    breadcrumb = _l("")

    def dispatch(self, request, *args, **kwargs):
        proj = get_r_object_or_404(self.request.user,
                                   Project,
                                   name_short=self.kwargs.get('project'))
        if not request.user.is_authenticated:
            return super(ProjectDetailTimelogView,
                         self).dispatch(request, *args, **kwargs)
        elif proj.activity_only_for_managers and not proj.is_manager(
                self.request.user):
            return HttpResponseRedirect(
                reverse_lazy('project:usertimelog',
                             kwargs={
                                 'project': proj.name_short,
                                 'username': self.request.user.username
                             }))
        return super(ProjectDetailTimelogView,
                     self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ProjectDetailTimelogView,
                        self).get_context_data(**kwargs)
        context['project'] = get_r_object_or_404(
            self.request.user, Project, name_short=self.kwargs.get('project'))
        devs = context['project'].get_members()
        context['logs'] = []
        devs = serializers.serialize("json", devs, fields=('username'))
        devs = json.loads(devs)

        for dev in devs:
            logs = Timelog.objects.filter(
                user=dev['pk'],
                issue__project=context['project']).order_by('-created_at')
            total_time = timedelta(0)
            for l in logs:
                total_time += l.time
            dev['fields']['total'] = total_time
            dev['fields']['logs'] = logs[:5]
            dev['fields']['ava_url'] = context['project'].get_members().filter(
                username=dev['fields']['username']).first().avatar.url

        context['developer'] = sorted(devs,
                                      key=lambda dev: dev['fields']['total'],
                                      reverse=True)
        return context

    def test_func(self):
        return get_r_object_or_404(self.request.user,
                                   Project,
                                   name_short=self.kwargs.get('project'))
Exemplo n.º 24
0
class ProjectUserTimelogView(LoginRequiredMixin, UserPassesTestMixin,
                             TemplateView):
    template_name = 'project/project_timelog_detail.html'
    breadcrumb = _l("")

    def dispatch(self, request, *args, **kwargs):
        proj = get_r_object_or_404(self.request.user,
                                   Project,
                                   name_short=self.kwargs.get('project'))
        if not request.user.is_authenticated:
            return super(ProjectUserTimelogView,
                         self).dispatch(request, *args, **kwargs)
        elif (proj.activity_only_for_managers
              and not proj.is_manager(request.user)
              and request.user.username != self.kwargs.get('username')):
            return HttpResponseRedirect(
                reverse_lazy('project:usertimelog',
                             kwargs={
                                 'project': proj.name_short,
                                 'username': self.request.user.username
                             }))
        return super(ProjectUserTimelogView,
                     self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ProjectUserTimelogView,
                        self).get_context_data(**kwargs)
        context['project'] = Project.objects.get(
            name_short=self.kwargs.get('project'))
        logs = Timelog.objects.filter(
            user__username=kwargs['username'],
            issue__project=context['project']).order_by('-created_at')
        dev = context['project'].get_members().filter(
            username=self.kwargs.get('username'))
        if dev.count() != 1:
            raise Http404
        paginator = Paginator(logs, 20)
        page = self.request.GET.get('page')
        try:
            logs = paginator.page(page)
        except PageNotAnInteger:
            logs = paginator.page(1)
        except EmptyPage:
            logs = paginator.page(paginator.num_pages)
        context['logs'] = logs

        context['ava_url'] = dev.first().avatar.url
        context['user'] = kwargs['username']
        return context

    def test_func(self):
        return get_r_object_or_404(self.request.user,
                                   Project,
                                   name_short=self.kwargs.get('project'))
Exemplo n.º 25
0
class FundingMA(ModelAdmin):
    model = FundingSnippet
    list_display = ('_agency', '_title', 'ag')

    def _agency(self, obj):
        agency = obj.agency
        if obj.project_number:
            return mark_safe('{agency}<br />{num}'.format(
                agency=agency, num=obj.project_number))
        else:
            return agency

    _agency.admin_order_field = 'agency'

    def _title(self, obj):
        title = obj.title

        if not title:
            if obj.title_en:
                title = obj.title_en
            elif obj.title_de:
                title = obj.title_de

        if obj.project_url:
            if obj.project_url.startswith(
                    'http://') or obj.project_url.startswith('https://'):
                url = obj.project_url
            else:
                url = 'http://{}'.format(obj.project_url)
            return mark_safe(
                '<a href="{url}" target="_new">{title}</a>'.format(
                    url=url, title=title))
        else:
            return title

    _title.short_description = _l('title')

    def ag(self, obj):
        return mark_safe(get_project_and_group(Project2FundingRelation, obj))

    ag.short_description = format_lazy('{}/{}', _l('Project'), _l('workgroup'))
Exemplo n.º 26
0
class Hours(models.Model):

    service_event = models.ForeignKey(
        ServiceEvent,
        on_delete=models.CASCADE,
        verbose_name=_l("service event"),
    )
    third_party = models.ForeignKey(
        ThirdParty,
        null=True,
        blank=True,
        on_delete=models.PROTECT,
        verbose_name=_l("third party"),
    )
    user = models.ForeignKey(
        User,
        null=True,
        blank=True,
        on_delete=models.PROTECT,
        verbose_name=_l("user"),
    )

    time = models.DurationField(
        _l("time"),
        help_text=_l('The time this person spent on this service event'),
    )

    class Meta:
        verbose_name = _l("hours")
        verbose_name_plural = _l("hours")
        unique_together = (
            'service_event',
            'third_party',
            'user',
        )

        default_permissions = ()
        permissions = (("can_have_hours", _l("Can have hours")), )

    def user_or_thirdparty(self):
        return self.user or self.third_party
Exemplo n.º 27
0
class PartUsed(models.Model):

    service_event = models.ForeignKey(
        sl_models.ServiceEvent,
        verbose_name=_l("service event"),
        help_text=_l("Select the Service Event the part was used in"),
        on_delete=models.CASCADE,
    )
    part = models.ForeignKey(
        Part,
        verbose_name=_l("part"),
        help_text=_l('Select the part used'),
        on_delete=models.CASCADE,
    )
    from_storage = models.ForeignKey(
        Storage,
        verbose_name=_l("from storage"),
        help_text=_l('Select which Storage the parts were taken from'),
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

    quantity = models.IntegerField(
        verbose_name=_l("quantity"),
        help_text=_l('Select how many parts were used from this Storage'),
    )

    def add_back_to_storage(self):

        if self.from_storage:
            try:
                psc = PartStorageCollection.objects.get(
                    part=self.part, storage=self.from_storage)
                psc.quantity += self.quantity
                psc.save()
            except PartStorageCollection.DoesNotExist:
                PartStorageCollection.objects.create(part=self.part,
                                                     storage=self.from_storage,
                                                     quantity=self.quantity)

    def remove_from_storage(self):

        if self.from_storage:
            try:
                psc = PartStorageCollection.objects.get(
                    part=self.part, storage=self.from_storage)
                psc.quantity -= self.quantity
                psc.save()
            except PartStorageCollection.DoesNotExist:
                pass
Exemplo n.º 28
0
class Contact(models.Model):

    supplier = models.ForeignKey(
        Supplier,
        verbose_name=_("supplier"),
        on_delete=models.CASCADE,
    )

    first_name = models.CharField(
        max_length=64,
        verbose_name=_("first name"),
        help_text=_l("Enter this persons first name"),
    )
    last_name = models.CharField(
        max_length=64,
        verbose_name=_("last name"),
        help_text=_l("Enter this persons last name"),
    )

    email = models.EmailField(
        verbose_name=_("email"),
        help_text=_l("Enter this persons email address"),
    )

    phone_number = models.CharField(
        verbose_name=_l("phone number"),
        blank=True,
        max_length=31,
        help_text=_l("Contact phone number"),
    )

    class Meta:
        verbose_name = _l('Contact')
        verbose_name_plural = _l('Contacts')
        unique_together = ('first_name', 'last_name', 'supplier')

    def __str__(self):
        return self.last_name + ', ' + self.first_name + ' (' + self.supplier.name + ')'

    def get_full_name(self):
        return str(self)
Exemplo n.º 29
0
class RUBIONUserInstrumentFilter(RAIFilter,
                                 metaclass=RUBIONUserInstrumentFilterMeta):
    label = _l('Used instruments')
    filter_id = 'user_instrument'
    is_mutual_exclusive = False
    help_text = _l('Filter users by their usage of instruments')

    def __init__(self, qs, value=None):
        super().__init__(qs, value)
        if self.value is not None:
            values = [int(val) for val in self.value]
            self.value = values

    def get_queryset(self):
        """
        Filters the users by their instrument usage
        """

        i2prfield = 'method2instrumentrelation_set__method__project2methodrelation_set__project_page'
        i2prval = 'method2instrumentrelation__method__project2methodrelation__project_page'
        instruments = InstrumentPage.objects.filter(pk__in=self.value)
        project_pks = instruments.prefetch_related(i2prfield).values_list(
            i2prval, flat=True).distinct()

        # the paths for the projects
        project_paths = Project.objects.filter(pk__in=project_pks,
                                               locked=False).values_list(
                                                   'path', flat=True)

        # In the tree, a project is 2 levels deeper than a workgroup, and one level is 4 digits in the
        # path. Thus, project_path[0:-8] gives the workgroups
        # use list(set(...)) to include only unique values

        workgroup_paths = list(set([pp[0:-8] for pp in project_paths]))

        # now make a Q-object from the paths
        q = Q()
        for wg in workgroup_paths:
            q |= Q(path__startswith=wg)

        return self.qs.filter(q)
Exemplo n.º 30
0
class TranslationListSerializer(serializers.ListSerializer):
    'A custom serializer to output translations in a nice dict'
    many = True
    default_error_messages = {
        'not_a_dict':
        _l('Expected a dictionary of items, but got a {input_type}.'),
    }

    def to_internal_value(self, data):
        if not isinstance(data, dict):
            message = self.error_messages['not_a_dict'].format(
                input_type=type(data).__name__)
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]})

        ret, errors = {}, {}
        for language, translation in data.items():
            try:
                validated = self.child.run_validation(translation)
            except ValidationError as exc:
                errors[language] = exc.detail
            else:
                ret[language] = validated
                errors[language] = {}
        if any(errors.values()):
            raise ValidationError(errors)
        return ret

    def get_attribute(self, instance):
        ''' Override get_attribute so it returns the whole translatable model and not just translations '''
        return instance

    def to_representation(self, instance):
        ''' Combine each translation in turn so the serializer has a full object '''
        result = {}
        stashed = get_cached_translation(instance)
        for translation in getattr(instance, self.source).all():
            set_cached_translation(instance, translation)
            result[translation.language_code] = self.child.to_representation(
                instance)
        set_cached_translation(instance, stashed)
        return result

    def save(self, *args, **kwargs):  #pragma: no cover
        raise NotImplementedError('TranslationList must be nested')

    @property
    def data(self):  #pragma: no cover
        raise NotImplementedError('TranslationList must be nested')

    @property
    def errors(self):  #pragma: no cover
        raise NotImplementedError('TranslationList must be nested')
Exemplo n.º 31
0
class ActiveDirectoryGroupMapAdmin(BaseQATrackAdmin):

    list_display = ("get_ad_group", "get_groups", "account_qualifier")
    list_filter = (
        "groups",
        "account_qualifier",
    )
    search_fields = ("ad_group", "groups__name")

    def get_groups(self, obj):
        return ', '.join(sorted(obj.groups.values_list("name", flat=True)))

    get_groups.short_description = _l("QATrack+ Groups")

    @mark_safe
    def get_ad_group(self, obj):
        if not obj.ad_group:
            return '<em>' + _("Default Groups") + "</em>"
        return escape(obj.ad_group)

    get_ad_group.short_description = _l("Active Directory Group Name")
Exemplo n.º 32
0
class PackageDownloadTask(models.Model):
    uuid = UUIDField(editable=False,
                     unique=True,
                     version=4,
                     help_text=_l("Unique identifier"))
    package = models.ForeignKey('Package', to_field='uuid')

    downloads_attempted = models.IntegerField(default=0)
    downloads_completed = models.IntegerField(default=0)
    download_completion_time = models.DateTimeField(default=None,
                                                    null=True,
                                                    blank=True)

    class Meta:
        verbose_name = _l("Package Download Task")
        app_label = 'locations'

    def __unicode__(self):
        return _(u'PackageDownloadTask ID: %(uuid)s for %(package)s') % {
            'uuid': self.uuid,
            'package': self.package
        }

    COMPLETE = 'complete'
    INCOMPLETE = 'incomplete'
    FAILED = 'failed'

    def downloading_status(self):
        """
        In order to determine the downloading status we need to check
        for three possibilities:
        1) The task involved no downloads. The downloads_attempted
           DB row column should be 0. This would be unusual, however,
           as there's no reason to make a task if not attempting
           to download anything.
        2) The task is downloading, but the downloading is not
           yet complete. downloads_attempted is greater than 0, but
           download_completion_time is not set.
        3) The task finished downloading and completed successfully.
           download_completion_time is set. downloads_attempted is
           equal to downloads_completed.
        4) The task finished downloading and completed unsuccessfully.
           download_completion_time is set. downloads_attempted isn't
           equal to downloads_completed.
        """
        if self.downloads_attempted == 0:
            return self.COMPLETE
        elif self.download_completion_time is None:
            return self.INCOMPLETE
        elif self.downloads_attempted == self.downloads_completed:
            return self.COMPLETE
        else:
            return self.FAILED
Exemplo n.º 33
0
def bootstrap_paginator(page_obj, link = None, href = None, page_dist = 2):
	control_last_page = page_obj.number + page_dist
	if control_last_page > page_obj.paginator.num_pages:
		control_last_page = page_obj.paginator.num_pages
	first_page = page_obj.number - 1 - page_dist
	if control_last_page - 1 - (page_dist * 2) < first_page:
		first_page = control_last_page - 1 - (page_dist * 2)
	if first_page < 0:
		first_page = 0

	last_page = first_page + (page_dist * 2) + 1
	page_range = page_obj.paginator.page_range[first_page:last_page]
	if not link and not href:
		raise ImproperlyConfigured(_l("both arguments \"link\" and \"href\" shouldn't be None. Please provide a \"link\" or \"href\" argument."))
	return {"page_obj": page_obj, "link": link, "href": href, "page_range": page_range}
Exemplo n.º 34
0
    (PURPOSE_SET_PASSWORD, 'set password'),
    (PURPOSE_SET_EMAIL, 'set email'),
    (PURPOSE_DELETE, 'delete'),
)
PURPOSE_DICT = dict(PURPOSE_CHOICES)

REGISTRATION_CHOICES = (
    (REGISTRATION_WEBSITE, 'Via Website'),
    (REGISTRATION_INBAND, 'In-Band Registration'),
    (REGISTRATION_UNKNOWN, 'Unknown'),
)
REGISTRATION_DICT = dict(REGISTRATION_CHOICES)
PURPOSES = {
    PURPOSE_REGISTER: {
        'urlname': 'RegistrationConfirmation',
        'subject': _l('Your new account on %(domain)s'),
        'template': 'register/mail',
    },
    PURPOSE_SET_EMAIL: {
        'urlname': 'ResetEmailConfirmation',
        'subject': _l('Confirm the email address for your %(domain)s account'),
        'template': 'reset/email-mail',
    },
    PURPOSE_SET_PASSWORD: {
        'urlname': 'ResetPasswordConfirmation',
        'subject': _l('Reset the password for your %(domain)s account'),
        'template': 'reset/password-mail',
    },
    PURPOSE_DELETE: {
        'urlname': 'DeleteConfirmation',
        'subject': _l('Delete your account on %(domain)s'),
Exemplo n.º 35
0
REGISTRATION_CHOICES = (
    (REGISTRATION_WEBSITE, 'Via Website'),
    (REGISTRATION_INBAND, 'In-Band Registration'),
    (REGISTRATION_UNKNOWN, 'Unknown'),
)
REGISTRATION_DICT = dict(REGISTRATION_CHOICES)
PURPOSES = {
    NEW_PURPOSE_REGISTER: {
        'subject': _('Your new account on %(domain)s'),
    },
    NEW_PURPOSE_SET_PASSWORD: {
        'subject':  _('Reset the password for your %(domain)s account'),
    },
    NEW_PURPOSE_SET_EMAIL: {
        'subject': _l('Confirm the email address for your %(domain)s account'),
    },
    NEW_PURPOSE_DELETE: {
        'subject': _l('Delete your account on %(domain)s'),
    },
}

log = logging.getLogger(__name__)
pgp_version = MIMENonMultipart('application', 'pgp-encrypted')
pgp_version.add_header('Content-Description', 'PGP/MIME version identification')
pgp_version.set_payload('Version: 1\n')


@python_2_unicode_compatible
class RegistrationUser(XmppBackendUser):
    # NOTE: MySQL only allows a 255 character limit