예제 #1
0
파일: views.py 프로젝트: mellterm/pootle
def tp_admin_files(request, translation_project):
    queryset = translation_project.stores.all()
    try:
        template_translation_project = TranslationProject.objects.get(project=translation_project.project,
                                                                      language__code='templates')
        if 'template_update' in request.GET:
            convert_templates(template_translation_project, translation_project)
    except TranslationProject.DoesNotExist:
        pass

    if 'scan_files' in request.GET:
        scan_translation_project_files(translation_project)
        for store in translation_project.stores.exclude(file='').iterator():
            store.sync(update_translation=True)
            store.update(update_structure=True, update_translation=True, conservative=False)

    model_args = {
        'title': _("Files"),
        'submitname': "changestores",
        'formid': "stores",
        'navitems': [navbar_dict.make_directory_navbar_dict(request, translation_project.directory)],
        'feed_path': translation_project.directory.pootle_path[1:],
        'translation_project': translation_project,
        'language': translation_project.language,
        'project': translation_project.project,
        'directory': translation_project.directory,
        }
    link = "%s/translate/"
    return util.edit(request, 'translation_project/tp_admin_files.html', Store, model_args,
                     link, linkfield='pootle_path', queryset=queryset,
                     formset=StoreFormset, can_delete=True, extra=0)
예제 #2
0
def view(request):
    fields = ('username', 'first_name', 'last_name', 'email', 'is_active',
              'is_superuser')
    queryset = User.objects.hide_defaults().order_by('username')
    return util.edit(request, 'admin/users.html', User, fields=fields,
                     formset=BaseUserFormSet, queryset=queryset,
                     can_delete=True)
예제 #3
0
def view(request):
    fields = ('username', 'first_name', 'last_name', 'email', 'is_active',
              'is_superuser')
    queryset = User.objects.hide_defaults().order_by('username')
    return util.edit(request, 'admin/admin_general_users.html', User,
                     fields=fields, formset=BaseUserFormSet, queryset=queryset,
                     can_delete=True)
예제 #4
0
파일: views.py 프로젝트: Jobava/pootle
def project_admin(request, current_project):
    """Adding and deleting project languages."""
    tp_form_class = tp_form_factory(current_project)

    queryset = TranslationProject.objects.filter(project=current_project)
    queryset = queryset.order_by('pootle_path')

    ctx = {
        'page': 'admin-languages',

        'project': {
            'code': current_project.code,
            'name': current_project.fullname,
        }
    }

    def generate_link(tp):
        path_args = split_pootle_path(tp.pootle_path)[:2]
        perms_url = reverse('pootle-tp-admin-permissions', args=path_args)
        return u'<a href="%s">%s</a>' % (perms_url, tp.language)

    extra = (1 if current_project.get_template_translationproject() is not None
               else 0)

    return util.edit(request, 'projects/admin/languages.html',
                     TranslationProject, ctx, generate_link,
                     linkfield="language", queryset=queryset,
                     can_delete=True, extra=extra, form=tp_form_class)
예제 #5
0
def tp_admin_files(request, translation_project):

    queryset = translation_project.stores.all()

    if 'template_update' in request.POST:
        translation_project.update_from_templates()
        request.POST = {}

    if 'scan_files' in request.POST:
        translation_project.scan_files()

        for store in translation_project.stores.exclude(file='').iterator():
            store.sync(update_translation=True)
            store.update(update_structure=True, update_translation=True,
                         conservative=False)

        request.POST = {}

    model_args = {
        'feed_path': translation_project.directory.pootle_path[1:],
        'translation_project': translation_project,
        'language': translation_project.language,
        'project': translation_project.project,
        'directory': translation_project.directory,
        }

    link = lambda instance: '<a href="%s/translate">%s</a>' % (
            l(instance.pootle_path),
            instance.pootle_path[len(translation_project.pootle_path):]
    )

    return util.edit(request, 'translation_project/tp_admin_files.html',
                     Store, model_args, link, linkfield='pootle_path',
                     queryset=queryset, formset=StoreFormset,
                     can_delete=True, extra=0)
예제 #6
0
def project_admin(request, current_project):
    """Adding and deleting project languages."""
    tp_form_class = tp_form_factory(current_project)

    queryset = TranslationProject.objects.filter(project=current_project)
    queryset = queryset.order_by('pootle_path')

    ctx = {
        'page': 'admin-languages',
        'project': {
            'code': current_project.code,
            'name': current_project.fullname,
        }
    }

    def generate_link(tp):
        path_args = split_pootle_path(tp.pootle_path)[:2]
        perms_url = reverse('pootle-tp-admin-permissions', args=path_args)
        return '<a href="%s">%s</a>' % (perms_url, tp.language)

    return util.edit(request,
                     'projects/admin/languages.html',
                     TranslationProject,
                     ctx,
                     generate_link,
                     linkfield="language",
                     queryset=queryset,
                     can_delete=True,
                     form=tp_form_class)
예제 #7
0
파일: views.py 프로젝트: Chipcius/pootle
def project_admin(request, current_project):
    """Adding and deleting project languages."""

    tp_form_class = tp_form_factory(current_project)

    queryset = TranslationProject.objects.filter(project=current_project) \
                                         .order_by('pootle_path')

    model_args = {
        'project': {
            'code': current_project.code,
            'name': current_project.fullname,
        }
    }

    link = lambda instance: '<a href="%s">%s</a>' % (
            l(instance.pootle_path + 'admin_permissions.html'),
            instance.language,
    )

    return util.edit(request, 'project/project_admin.html', TranslationProject,
                     model_args, link, linkfield="language", queryset=queryset,
                     can_delete=True, form=tp_form_class,
                     formset=TranslationProjectFormSet,
                     exclude=('description',))
예제 #8
0
def view(request):
    queryset = Language.objects.exclude(code='templates')
    try:
        default_lang = Language.objects.get(code='en')
    except Language.DoesNotExist:
        default_lang = queryset[0]


    class ProjectForm(forms.ModelForm):
        class Meta:
            model = Project

        source_language = forms.ModelChoiceField(label=_('Source Language'),
                initial=default_lang.pk, queryset=queryset)

        def __init__(self, *args, **kwargs):
            super(ProjectForm, self).__init__(*args, **kwargs)
            if self.instance.id:
                has_stores = Store.objects.filter(
                        translation_project__project=self.instance
                    ).count
                if has_stores:
                    self.fields['localfiletype'].widget.attrs['disabled'] = True
                    self.fields['localfiletype'].required = False
                if (self.instance.treestyle != 'auto' and
                    self.instance.translationproject_set.count() and
                    self.instance.treestyle ==
                        self.instance._detect_treestyle()):
                    self.fields['treestyle'].widget.attrs['disabled'] = True
                    self.fields['treestyle'].required = False
            self.fields['checkstyle'].widget.attrs['class'] = \
                "js-select2 select2-checkstyle"
            self.fields['localfiletype'].widget.attrs['class'] = \
                "js-select2 select2-localfiletype"
            self.fields['treestyle'].widget.attrs['class'] = \
                "js-select2 select2-treestyle"
            self.fields['source_language'].widget.attrs['class'] = \
                "js-select2 select2-language"

        def clean_localfiletype(self):
            value = self.cleaned_data.get('localfiletype', None)
            if not value:
                value = self.instance.localfiletype
            return value

        def clean_treestyle(self):
            value = self.cleaned_data.get('treestyle', None)
            if not value:
                value = self.instance.treestyle
            return value

    return util.edit(
            request,
            'admin/admin_general_projects.html',
            Project,
            link='/projects/%s/admin.html',
            form=ProjectForm,
            exclude=('description', 'report_target'),
            can_delete=True,
    )
def admin_permissions(request, current_directory, template, context):
    content_type = ContentType.objects.get(name='pootle', app_label='pootle_app')
    permission_queryset = content_type.permission_set.exclude(codename__in=['add_directory', 'change_directory', 'delete_directory'])

    context['submitname'] = 'changepermissions'
    context['formid'] = 'permission-manage'

    project = context.get('project', None)
    language = context.get('language', None)

    base_queryset = PootleProfile.objects.filter(user__is_active=1).exclude(id__in=current_directory.permission_sets.values_list('profile_id', flat=True))
    querysets = [(None, base_queryset.filter(user__username__in=('nobody', 'default')))]
    if project is not None:
        if language is not None:
            querysets.append((_('Project Members'), base_queryset.filter(projects=project, languages=language).order_by('user__username')))
        else:
            querysets.append((_('Project Members'), base_queryset.filter(projects=project).order_by('user__username')))
    if language is not None:
        querysets.append((_('Language Members'), base_queryset.filter(languages=language).order_by('user__username')))
    querysets.append((_('All Users'), base_queryset.exclude(user__username__in=('nobody', 'default')).order_by('user__username')))

    class PermissionSetForm(forms.ModelForm):
        class Meta:
            model = PermissionSet

        directory = forms.ModelChoiceField(queryset=Directory.objects.filter(pk=current_directory.pk),
                                           initial=current_directory.pk, widget=forms.HiddenInput)
        profile = GroupedModelChoiceField(querysets=querysets, queryset=PootleProfile.objects.all(), required=True)
        positive_permissions = PermissionFormField(label=_('Permissions'), queryset=permission_queryset, required=False)

    link = lambda instance: unicode(instance.profile)
    return util.edit(request, template, PermissionSet, context, link, linkfield='profile',
              queryset=current_directory.permission_sets.order_by('profile').all(), can_delete=True,
              form=PermissionSetForm)
예제 #10
0
파일: views.py 프로젝트: JMassapina/pootle
def project_admin(request, current_project):
    """Adding and deleting project languages."""

    tp_form_class = tp_form_factory(current_project)

    queryset = TranslationProject.objects.filter(project=current_project) \
                                         .order_by('pootle_path')

    model_args = {
        'project': {
            'code': current_project.code,
            'name': current_project.fullname,
        }
    }

    def generate_link(tp):
        path_args = split_pootle_path(tp.pootle_path)[:2]
        perms_url = reverse('pootle-tp-admin-permissions', args=path_args)
        return '<a href="%s">%s</a>' % (perms_url, tp.language)

    return util.edit(request, 'projects/admin/languages.html',
                     TranslationProject, model_args, generate_link,
                     linkfield="language", queryset=queryset,
                     can_delete=True, form=tp_form_class,
                     formset=TranslationProjectFormSet,
                     exclude=('description',))
예제 #11
0
def admin_permissions(request, current_directory, template, context):
    content_type = ContentType.objects.get(name='pootle', app_label='pootle_app')
    permission_queryset = content_type.permission_set.exclude(codename__in=['add_directory', 'change_directory', 'delete_directory'])

    context['submitname'] = 'changepermissions'
    context['formid'] = 'permission-manage'

    project = context.get('project', None)
    language = context.get('language', None)

    base_queryset = PootleProfile.objects.filter(user__is_active=1).exclude(id__in=current_directory.permission_sets.values_list('profile_id', flat=True))
    querysets = [(None, base_queryset.filter(user__username__in=('nobody', 'default')))]
    if project is not None:
        if language is not None:
            querysets.append((_('Project Members'), base_queryset.filter(projects=project, languages=language).order_by('user__username')))
        else:
            querysets.append((_('Project Members'), base_queryset.filter(projects=project).order_by('user__username')))
    if language is not None:
        querysets.append((_('Language Members'), base_queryset.filter(languages=language).order_by('user__username')))
    querysets.append((_('All Users'), base_queryset.exclude(user__username__in=('nobody', 'default')).order_by('user__username')))

    class PermissionSetForm(forms.ModelForm):
        class Meta:
            model = PermissionSet
            exclude = ['negative_permissions']

        directory = forms.ModelChoiceField(queryset=Directory.objects.filter(pk=current_directory.pk),
                                           initial=current_directory.pk, widget=forms.HiddenInput)
        profile = GroupedModelChoiceField(querysets=querysets, queryset=PootleProfile.objects.all(), required=True)
        positive_permissions = PermissionFormField(label=_('Permissions'), queryset=permission_queryset, required=False)

    link = lambda instance: unicode(instance.profile)
    return util.edit(request, template, PermissionSet, context, link, linkfield='profile',
              queryset=current_directory.permission_sets.order_by('profile').all(), can_delete=True,
              form=PermissionSetForm)
def view(request):
    model_args = {}
    model_args['title'] = _("Languages")
    model_args['submitname'] = "changelanguages"
    model_args['formid'] = "languages"
    link = '/%s/admin.html'
    return util.edit(request, 'admin/admin_general_languages.html', Language, model_args, link,
                     form=MyLanguageAdminForm, can_delete=True)
예제 #13
0
def view(request):
    return util.edit(request,
                     'admin/admin_general_languages.html',
                     Language,
                     link='/%s/admin.html',
                     form=MyLanguageAdminForm,
                     exclude='description',
                     can_delete=True)
예제 #14
0
def view(request):
    model_args = {}
    model_args['title'] = _("Projects")
    model_args['formid'] = "projects"
    model_args['submitname'] = "changeprojects"
    link = '/projects/%s/admin.html'
    return util.edit(request, 'admin/admin_general_projects.html', Project, model_args, link,
              form=MyProjectAdminForm, exclude='description', can_delete=True)
예제 #15
0
def view(request):
    model_args = {}
    model_args['title'] = _("Users")
    model_args['submitname'] = "changeusers"
    model_args['formid'] = "users"
    return util.edit(request, 'admin/admin_general_users.html', User, model_args,
               fields=('username', 'first_name', 'last_name', 'email', 'is_active', 'is_superuser'),
               formset=BaseUserFormSet, queryset=User.objects.hide_defaults().order_by('username'), can_delete=True)
예제 #16
0
def view(request):
    fields = ("username", "full_name", "email", "is_active", "is_superuser")
    queryset = User.objects.hide_defaults().order_by('username')
    return util.edit(request,
                     'admin/users.html',
                     User,
                     fields=fields,
                     formset=BaseUserFormSet,
                     queryset=queryset,
                     can_delete=True)
예제 #17
0
def view(request):

    def generate_link(language):
        url = reverse('pootle-language-admin-permissions',
                      args=[language.code])
        return '<a href="%s">%s</a>' % (url, language)

    return util.edit(request, 'admin/languages.html', Language,
                     link=generate_link, form=LanguageAdminForm,
                     exclude=('description', ), can_delete=True)
예제 #18
0
def view(request):

    def generate_link(language):
        url = reverse('pootle-language-admin-permissions',
                      args=[language.code])
        return '<a href="%s">%s</a>' % (url, language)

    return util.edit(request, 'admin/languages.html', Language,
                     link=generate_link, form=LanguageAdminForm,
                     exclude=('description', ), can_delete=True)
예제 #19
0
def manage_store(request, template_vars, language, term_store):
    from django import forms
    from pootle_store.forms import unit_form_factory
    unit_form_class = unit_form_factory(language)

    # XXX: Review this
    # HACKISH: Django won't allow excluding form fields already defined in
    # the parent class, manually extra fields.
    del (unit_form_class.base_fields['target_f'])
    del (unit_form_class.base_fields['id'])
    del (unit_form_class.base_fields['state'])
    del (unit_form_class.declared_fields['target_f'])
    del (unit_form_class.declared_fields['id'])
    del (unit_form_class.declared_fields['state'])

    class TermUnitForm(unit_form_class):
        # Set store for new terms
        qs = Store.objects.filter(pk=term_store.pk)
        store = forms.ModelChoiceField(queryset=qs,
                                       initial=term_store.pk,
                                       widget=forms.HiddenInput)
        index = forms.IntegerField(required=False, widget=forms.HiddenInput)

        def clean_index(self):
            # Assign new terms an index value
            value = self.cleaned_data['index']

            if self.instance.id is None:
                value = term_store.max_index() + 1
            return value

        def clean_source_f(self):
            value = super(TermUnitForm, self).clean_source_f()

            if value:
                existing = term_store.findid(value[0])

                if existing and existing.id != self.instance.id:
                    raise forms.ValidationError(
                        _('This term already exists '
                          'in this file.'))
                self.instance.setid(value[0])

            return value

    return util.edit(request,
                     'terminology/manage.html',
                     Unit,
                     template_vars,
                     None,
                     None,
                     queryset=term_store.units,
                     can_delete=True,
                     form=TermUnitForm,
                     exclude=['state', 'target_f', 'id', 'translator_comment'])
예제 #20
0
def project_admin(request, project_code):
    """adding and deleting project languages"""
    current_project = Project.objects.get(code=project_code)
    request.permissions = get_matching_permissions(
        get_profile(request.user), current_project.directory)
    if not check_permission('administrate', request):
        raise PermissionDenied(_(
            "You do not have rights to administer this project."))

    template_translation_project = current_project. \
                                   get_template_translationproject()

    class TranslationProjectForm(forms.ModelForm):
        if template_translation_project is not None:
            update = forms.BooleanField(required=False, label=_(
                "Update from templates"))
        #FIXME: maybe we can detect if initialize is needed to avoid
        # displaying it when not relevant
        # initialize = forms.BooleanField(
        #     required=False, label=_("Initialize"))
        project = forms.ModelChoiceField(
            queryset=Project.objects.filter(pk=current_project.pk),
            initial=current_project.pk, widget=forms.HiddenInput)
        language = LiberalModelChoiceField(
            label=_("Language"),
            queryset=Language.objects.exclude(
                translationproject__project=current_project))
        class Meta:
            prefix = "existing_language"
            model = TranslationProject

        def process_extra_fields(self):
            if self.instance.pk is not None:
                if self.cleaned_data.get('initialize', None):
                    self.instance.initialize()

                if self.cleaned_data.get('update', None) or not \
                       self.instance.stores.count():
                    self.instance.update_from_templates()

    queryset = TranslationProject.objects.filter(
        project=current_project).order_by('pootle_path')
    model_args = {}
    model_args['project'] = {'code': current_project.code,
                             'name': current_project.fullname}
    model_args['formid'] = "translation-projects"
    model_args['submitname'] = "changetransprojects"
    link = lambda instance: '<a href="/wikitrans%s">%s</a>' % (
        l(instance.pootle_path + 'admin_permissions.html'), instance.language)
    return util.edit(
        request, 'project/project_admin.html', TranslationProject,
        model_args, link, linkfield="language",
        queryset=queryset, can_delete=True, form=TranslationProjectForm,
        formset=TranslationProjectFormSet)
예제 #21
0
def view(request):
    queryset = Language.objects.exclude(code='templates')
    try:
        default_lang = Language.objects.get(code='en')
    except Language.DoesNotExist:
        default_lang = queryset[0]

    class ProjectForm(forms.ModelForm):
        class Meta:
            model = Project

        source_language = forms.ModelChoiceField(label=_('Source Language'),
                                                 initial=default_lang.pk,
                                                 queryset=queryset)

        def __init__(self, *args, **kwargs):
            super(ProjectForm, self).__init__(*args, **kwargs)
            if self.instance.id:
                if Store.objects.filter(
                        translation_project__project=self.instance).count():
                    self.fields['localfiletype'].widget.attrs[
                        'disabled'] = True
                    self.fields['localfiletype'].required = False
                if self.instance.treestyle != 'auto' and self.instance.translationproject_set.count() and \
                       self.instance.treestyle == self.instance._detect_treestyle():
                    self.fields['treestyle'].widget.attrs['disabled'] = True
                    self.fields['treestyle'].required = False

        def clean_localfiletype(self):
            value = self.cleaned_data.get('localfiletype', None)
            if not value:
                value = self.instance.localfiletype
            return value

        def clean_treestyle(self):
            value = self.cleaned_data.get('treestyle', None)
            if not value:
                value = self.instance.treestyle
            return value

    model_args = {}
    model_args['title'] = _("Projects")
    model_args['formid'] = "projects"
    model_args['submitname'] = "changeprojects"
    link = '/projects/%s/admin.html'
    return util.edit(request,
                     'admin/admin_general_projects.html',
                     Project,
                     model_args,
                     link,
                     form=ProjectForm,
                     exclude='description',
                     can_delete=True)
예제 #22
0
def manage_store(request, ctx, language, term_store):
    from django import forms
    from pootle_store.forms import unit_form_factory
    unit_form_class = unit_form_factory(language)

    # XXX: Review this
    # HACKISH: Django won't allow excluding form fields already defined in
    # the parent class, manually extra fields.
    del(unit_form_class.base_fields['target_f'])
    del(unit_form_class.base_fields['id'])
    del(unit_form_class.base_fields['state'])
    del(unit_form_class.declared_fields['target_f'])
    del(unit_form_class.declared_fields['id'])
    del(unit_form_class.declared_fields['state'])

    class TermUnitForm(unit_form_class):
        # Set store for new terms.
        qs = Store.objects.filter(pk=term_store.pk)
        store = forms.ModelChoiceField(queryset=qs, initial=term_store.pk,
                                       widget=forms.HiddenInput)
        index = forms.IntegerField(required=False, widget=forms.HiddenInput)

        def clean_index(self):
            # Assign new terms an index value.
            value = self.cleaned_data['index']

            if self.instance.id is None:
                value = term_store.max_index() + 1
            return value

        def clean_source_f(self):
            value = super(TermUnitForm, self).clean_source_f()

            if value:
                existing = term_store.findid(value[0])

                if existing and existing.id != self.instance.id:
                    raise forms.ValidationError(_('This term already exists '
                                                  'in this file.'))
                self.instance.setid(value[0])

            return value

    #TODO 'submitted_by' and 'commented_by' had to be excluded in order to get
    # terminology editing working. When the schema can be changed again this
    # exclusion should be removed and change the schema accordingly.
    excluded_fields = ['state', 'target_f', 'id', 'translator_comment',
                       'submitted_by', 'commented_by']
    template_name = 'translation_projects/terminology/manage.html'

    return util.edit(request, template_name, Unit, ctx,
                     None, None, queryset=term_store.units, can_delete=True,
                     form=TermUnitForm, exclude=excluded_fields)
예제 #23
0
파일: views.py 프로젝트: iSCGroup/pootle
def manage_store(request, ctx, language, term_store):
    from django import forms
    from pootle_store.forms import unit_form_factory
    unit_form_class = unit_form_factory(language)

    # XXX: Review this
    # HACKISH: Django won't allow excluding form fields already defined in
    # the parent class, manually extra fields.
    del(unit_form_class.base_fields['target_f'])
    del(unit_form_class.base_fields['id'])
    del(unit_form_class.base_fields['state'])
    del(unit_form_class.declared_fields['target_f'])
    del(unit_form_class.declared_fields['id'])
    del(unit_form_class.declared_fields['state'])

    class TermUnitForm(unit_form_class):
        # Set store for new terms.
        qs = Store.objects.filter(pk=term_store.pk)
        store = forms.ModelChoiceField(queryset=qs, initial=term_store.pk,
                                       widget=forms.HiddenInput)
        index = forms.IntegerField(required=False, widget=forms.HiddenInput)

        def clean_index(self):
            # Assign new terms an index value.
            value = self.cleaned_data['index']

            if self.instance.id is None:
                value = term_store.max_index() + 1
            return value

        def clean_source_f(self):
            value = super(TermUnitForm, self).clean_source_f()

            if value:
                existing = term_store.findid(value[0])

                if existing and existing.id != self.instance.id:
                    raise forms.ValidationError(_('This term already exists '
                                                  'in this file.'))
                self.instance.setid(value[0])

            return value

    #TODO 'submitted_by' and 'commented_by' had to be excluded in order to get
    # terminology editing working. When the schema can be changed again this
    # exclusion should be removed and change the schema accordingly.
    excluded_fields = ['state', 'target_f', 'id', 'translator_comment',
                       'submitted_by', 'commented_by']
    template_name = 'translation_projects/terminology/manage.html'

    return util.edit(request, template_name, Unit, ctx,
                     None, None, queryset=term_store.units, can_delete=True,
                     form=TermUnitForm, exclude=excluded_fields)
예제 #24
0
def manage(request, translation_project):
    template_vars = {
        "translation_project": translation_project,
        "language": translation_project.language,
        "project": translation_project.project,
        "source_language": translation_project.project.source_language,
        "directory": translation_project.directory,
        'formid': 'terminology-manage',
        'submitname': 'changeterminology',
        }
    try:
        terminology_filename = get_terminology_filename(translation_project)
        term_store = Store.objects.get(pootle_path=translation_project.pootle_path + terminology_filename)
        template_vars['store'] = term_store

        #HACKISH: Django won't allow excluding form fields already defined in parent class, manually extra fields.
        unit_form_class = unit_form_factory(translation_project.language, 1)
        del(unit_form_class.base_fields['target_f'])
        del(unit_form_class.base_fields['id'])
        del(unit_form_class.base_fields['translator_comment'])
        del(unit_form_class.base_fields['state'])
        del(unit_form_class.declared_fields['target_f'])
        del(unit_form_class.declared_fields['id'])
        del(unit_form_class.declared_fields['translator_comment'])
        del(unit_form_class.declared_fields['state'])

        class TermUnitForm(unit_form_class):
            # set store for new terms
            store = forms.ModelChoiceField(queryset=Store.objects.filter(pk=term_store.pk), initial=term_store.pk, widget=forms.HiddenInput)
            index = forms.IntegerField(required=False, widget=forms.HiddenInput)

            def clean_index(self):
                # assign new terms an index value
                value = self.cleaned_data['index']
                if self.instance.id is None:
                    value = term_store.max_index() + 1
                return value

            def clean_source_f(self):
                value = super(TermUnitForm, self).clean_source_f()
                if value:
                    existing = term_store.findid(value[0])
                    if existing and existing.id != self.instance.id:
                        raise forms.ValidationError(_('Please correct the error below.'))
                    self.instance.setid(value[0])
                return value

        return util.edit(request, 'terminology/manage.html', Unit, template_vars, None, None,
                         queryset=term_store.units, can_delete=True, form=TermUnitForm,
                         exclude=['state', 'target_f', 'id', 'translator_comment'])
    except Store.DoesNotExist:
        return render_to_response("terminology/manage.html", template_vars,
                                  context_instance=RequestContext(request))
예제 #25
0
파일: views.py 프로젝트: shayanb/pootle
def manage_store(request, ctx, language, term_store):
    TermUnitForm = term_unit_form_factory(term_store)
    template_name = 'translation_projects/terminology/manage.html'
    return util.edit(request,
                     template_name,
                     Unit,
                     ctx,
                     None,
                     None,
                     queryset=term_store.units,
                     can_delete=True,
                     form=TermUnitForm)
예제 #26
0
def view(request):
    queryset = Language.objects.exclude(code='templates')
    try:
        default_lang = Language.objects.get(code='en')
    except Language.DoesNotExist:
        default_lang = queryset[0]


    class ProjectForm(forms.ModelForm):
        class Meta:
            model = Project

        source_language = forms.ModelChoiceField(
            label=_('Source Language'), initial=default_lang.pk,
            queryset=queryset)

        def __init__(self, *args, **kwargs):
            super(ProjectForm, self).__init__(*args, **kwargs)
            if self.instance.id:
                if Store.objects.filter(
                    translation_project__project=self.instance).count():
                    self.fields['localfiletype'].widget.attrs['disabled'] = \
                                                                          True
                    self.fields['localfiletype'].required = False
                if self.instance.treestyle != 'auto' and \
                       self.instance.translationproject_set.count() and \
                       self.instance.treestyle == \
                       self.instance._detect_treestyle():
                    self.fields['treestyle'].widget.attrs['disabled'] = True
                    self.fields['treestyle'].required = False

        def clean_localfiletype(self):
            value = self.cleaned_data.get('localfiletype', None)
            if not value:
                value = self.instance.localfiletype
            return value

        def clean_treestyle(self):
            value = self.cleaned_data.get('treestyle', None)
            if not value:
                value = self.instance.treestyle
            return value


    model_args = {}
    model_args['title'] = _("Projects")
    model_args['formid'] = "projects"
    model_args['submitname'] = "changeprojects"
    link = '/wikitrans/projects/%s/admin.html'
    return util.edit(
        request, 'admin/admin_general_projects.html', Project, model_args,
        link, form=ProjectForm, exclude='description', can_delete=True)
예제 #27
0
def manage(request, translation_project):
    template_vars = {
        "translation_project": translation_project,
        "language": translation_project.language,
        "project": translation_project.project,
        "source_language": translation_project.project.source_language,
        "directory": translation_project.directory,
        'formid': 'terminology-manage',
        'submitname': 'changeterminology'
        }
    try:
        term_store = Store.objects.get(pootle_path=translation_project.pootle_path + 'pootle-terminology.po')
        template_vars['store'] = term_store

        #HACKISH: Django won't allow excluding form fields already defined in parent class, manually extra fields.
        unit_form_class = unit_form_factory(translation_project.language, 1)
        del(unit_form_class.base_fields['target_f'])
        del(unit_form_class.base_fields['id'])
        del(unit_form_class.base_fields['translator_comment'])
        del(unit_form_class.base_fields['state'])
        del(unit_form_class.declared_fields['target_f'])
        del(unit_form_class.declared_fields['id'])
        del(unit_form_class.declared_fields['translator_comment'])
        del(unit_form_class.declared_fields['state'])

        class TermUnitForm(unit_form_class):
            # set store for new terms
            store = forms.ModelChoiceField(queryset=Store.objects.filter(pk=term_store.pk), initial=term_store.pk, widget=forms.HiddenInput)
            index = forms.IntegerField(required=False, widget=forms.HiddenInput)

            def clean_index(self):
                # assign new terms an index value
                value = self.cleaned_data['index']
                if self.instance.id is None:
                    value = term_store.max_index() + 1
                return value

            def clean_source_f(self):
                value = super(TermUnitForm, self).clean_source_f()
                if value:
                    existing = term_store.findid(value[0])
                    if existing and existing.id != self.instance.id:
                        raise forms.ValidationError(_('Please correct the error below.'))
                    self.instance.setid(value[0])
                return value

        return util.edit(request, 'terminology/manage.html', Unit, template_vars, None, None,
                         queryset=term_store.units, can_delete=True, form=TermUnitForm,
                         exclude=['state', 'target_f', 'id', 'translator_comment'])
    except Store.DoesNotExist:
        return render_to_response("terminology/manage.html", template_vars,
                                  context_instance=RequestContext(request))
def view(request):
    model_args = {}
    model_args['title'] = _("Languages")
    model_args['submitname'] = "changelanguages"
    model_args['formid'] = "languages"
    link = '/%s/admin.html'
    return util.edit(request,
                     'admin/admin_general_languages.html',
                     Language,
                     model_args,
                     link,
                     form=MyLanguageAdminForm,
                     can_delete=True)
예제 #29
0
def tp_admin_files(request, translation_project):
    queryset = translation_project.stores.all()
    if 'template_update' in request.POST:
        translation_project.update_from_templates()
        request.POST = {}

    if 'scan_files' in request.POST:
        translation_project.scan_files()
        for store in translation_project.stores.exclude(file='').iterator():
            store.sync(update_translation=True)
            store.update(update_structure=True,
                         update_translation=True,
                         conservative=False)
        request.POST = {}

    model_args = {
        'title':
        _("Files"),
        'submitname':
        "changestores",
        'formid':
        "stores",
        'navitems': [
            navbar_dict.make_directory_navbar_dict(
                request, translation_project.directory)
        ],
        'feed_path':
        translation_project.directory.pootle_path[1:],
        'translation_project':
        translation_project,
        'language':
        translation_project.language,
        'project':
        translation_project.project,
        'directory':
        translation_project.directory,
    }
    link = lambda instance: '<a href="%s/translate">%s</a>' % (l(
        instance.pootle_path), instance.pootle_path[len(translation_project.
                                                        pootle_path):])

    return util.edit(request,
                     'translation_project/tp_admin_files.html',
                     Store,
                     model_args,
                     link,
                     linkfield='pootle_path',
                     queryset=queryset,
                     formset=StoreFormset,
                     can_delete=True,
                     extra=0)
예제 #30
0
def view(request):
    def generate_link(project):
        url = reverse("pootle-project-admin-languages", args=[project.code])
        return '<a href="%s">%s</a>' % (url, project.code)

    return util.edit(
        request,
        "admin/projects.html",
        Project,
        link=generate_link,
        form=project_admin_form_factory(),
        exclude=("description", "report_email"),
        can_delete=True,
    )
예제 #31
0
def view(request):
    def generate_link(project):
        url = reverse('pootle-project-admin-languages', args=[project.code])
        return '<a href="%s">%s</a>' % (url, project.code)

    return util.edit(
        request,
        'admin/projects.html',
        Project,
        link=generate_link,
        form=project_admin_form_factory(),
        exclude=('description', 'report_email'),
        can_delete=True,
    )
예제 #32
0
def view(request):
    model_args = {}
    model_args['title'] = _("Users")
    model_args['submitname'] = "changeusers"
    model_args['formid'] = "users"
    return util.edit(
        request,
        'admin/admin_general_users.html',
        User,
        model_args,
        fields=('username', 'first_name', 'last_name', 'email', 'is_active',
                'is_superuser'),
        formset=BaseUserFormSet,
        queryset=User.objects.hide_defaults().order_by('username'),
        can_delete=True)
예제 #33
0
def project_admin(request, current_project):
    """Adding and deleting project languages."""
    tp_form_class = tp_form_factory(current_project)

    queryset = TranslationProject.objects.filter(project=current_project)
    queryset = queryset.order_by('pootle_path')

    ctx = {
        'page':
        'admin-languages',
        'browse_url':
        reverse('pootle-project-browse',
                kwargs={
                    'project_code': current_project.code,
                    'dir_path': '',
                    'filename': '',
                }),
        'translate_url':
        reverse('pootle-project-translate',
                kwargs={
                    'project_code': current_project.code,
                    'dir_path': '',
                    'filename': '',
                }),
        'project': {
            'code': current_project.code,
            'name': current_project.fullname,
        }
    }

    def generate_link(tp):
        path_args = split_pootle_path(tp.pootle_path)[:2]
        perms_url = reverse('pootle-tp-admin-permissions', args=path_args)
        return u'<a href="%s">%s</a>' % (perms_url, tp.language)

    extra = (1 if current_project.get_template_translationproject() is not None
             else 0)

    return util.edit(request,
                     'projects/admin/languages.html',
                     TranslationProject,
                     ctx,
                     generate_link,
                     linkfield="language",
                     queryset=queryset,
                     can_delete=True,
                     extra=extra,
                     form=tp_form_class)
예제 #34
0
파일: views.py 프로젝트: avivian/pootle
def manage_store(request, template_vars, language, term_store):
    from django import forms
    from pootle_store.forms import unit_form_factory
    unit_form_class = unit_form_factory(language)

    # XXX: Review this
    # HACKISH: Django won't allow excluding form fields already defined in
    # the parent class, manually extra fields.
    del(unit_form_class.base_fields['target_f'])
    del(unit_form_class.base_fields['id'])
    del(unit_form_class.base_fields['state'])
    del(unit_form_class.declared_fields['target_f'])
    del(unit_form_class.declared_fields['id'])
    del(unit_form_class.declared_fields['state'])

    class TermUnitForm(unit_form_class):
        # Set store for new terms
        qs = Store.objects.filter(pk=term_store.pk)
        store = forms.ModelChoiceField(queryset=qs, initial=term_store.pk,
                                       widget=forms.HiddenInput)
        index = forms.IntegerField(required=False, widget=forms.HiddenInput)

        def clean_index(self):
            # Assign new terms an index value
            value = self.cleaned_data['index']

            if self.instance.id is None:
                value = term_store.max_index() + 1
            return value

        def clean_source_f(self):
            value = super(TermUnitForm, self).clean_source_f()

            if value:
                existing = term_store.findid(value[0])

                if existing and existing.id != self.instance.id:
                    raise forms.ValidationError(_('This term already exists '
                                                  'in this file.'))
                self.instance.setid(value[0])

            return value

    return util.edit(request, 'terminology/manage.html', Unit, template_vars, None, None,
                     queryset=term_store.units, can_delete=True, form=TermUnitForm,
                     exclude=['state', 'target_f', 'id', 'translator_comment'])
예제 #35
0
def view(request):
    """Edit feature flags.

    This view is intended to allow tying users to the existing flags, allowing
    them to use the features enabled by this flags. Flags are hardcoded, but if
    it is necessary to edit them beyond changing the users the flags are tied
    to, it is possible to alter them through the Django admin site.
    """

    class FeatureFlagForm(forms.ModelForm):
        # We don't want to show the 'superusers' field, but is necessary for
        # overriding its default value.
        superusers = forms.BooleanField(initial=False, required=False,
            widget=forms.HiddenInput()
        )

        class Meta:
            model = Flag
            widgets = {
                'name': forms.TextInput(attrs={
                    'class': 'feature-non-editable',
                    'readonly': True,
                }),
                'users': forms.SelectMultiple(attrs={
                    'class': 'js-select2 select2-multiple',
                    'data-placeholder': _('Select one or more users'),
                }),
                'note': forms.TextInput(attrs={
                    'size': 60,
                    'class': 'feature-non-editable',
                    'readonly': True,
                }),
            }

    fields = ('name', 'superusers', 'users', 'note')
    queryset = Flag.objects.order_by('-id')

    return util.edit(request, 'admin/admin_general_features.html', Flag,
                     form=FeatureFlagForm, fields=fields, queryset=queryset,
                     can_delete=True, extra=0)
예제 #36
0
def view(request):
    return util.edit(request, 'admin/admin_general_languages.html', Language,
                     link='/%s/admin.html', form=MyLanguageAdminForm,
                     exclude='description', can_delete=True)
예제 #37
0
def admin_permissions(request, current_directory, template, context):
    project = context.get('project', None)
    language = context.get('language', None)

    # FIXME: Shouldn't we just remove unused permissions from the DB?
    excluded_permissions = [
        'add_directory',
        'change_directory',
        'delete_directory',
    ]
    # Don't provide means to add `view` permissions under /<lang_code>/*
    # In other words: only allow setting `view` permissions for the root
    # and the `/projects/<code>/` directories
    if language is not None:
        excluded_permissions.append('view')

    content_type = get_permission_contenttype()
    permission_queryset = content_type.permission_set.exclude(
        codename__in=excluded_permissions, )

    base_queryset = PootleProfile.objects.filter(user__is_active=1).exclude(
            id__in=current_directory.permission_sets \
                                    .values_list('profile_id', flat=True),
    )
    querysets = [
        (None, base_queryset.filter(user__username__in=('nobody', 'default')))
    ]

    if project is not None:
        if language is not None:
            group_label = _('Translation Project Contributors')
            tp_path = '/%s/%s/' % (language.code, project.code)
            contributions = Submission.objects.filter(
                translation_project__pootle_path=tp_path, )
        else:
            group_label = _('Project Contributors')
            contributions = Submission.objects.filter(
                translation_project__project__code=project.code, )

        querysets.append((
            group_label,
            base_queryset.filter(submission__in=contributions).distinct().
            order_by('user__username'),
        ))

    if language is not None:
        contributions = Submission.objects.filter(
            translation_project__language__code=language.code, )
        querysets.append((
            _('Language Contributors'),
            base_queryset.filter(submission__in=contributions).distinct().
            order_by('user__username'),
        ))

    querysets.append((
        _('All Users'),
        base_queryset.exclude(
            user__username__in=('nobody',
                                'default')).order_by('user__username'),
    ))

    class PermissionSetForm(forms.ModelForm):
        class Meta:
            model = PermissionSet

        directory = forms.ModelChoiceField(
            queryset=Directory.objects.filter(pk=current_directory.pk),
            initial=current_directory.pk,
            widget=forms.HiddenInput,
        )
        profile = GroupedModelChoiceField(
            label=_('Username'),
            querysets=querysets,
            queryset=PootleProfile.objects.all(),
            required=True,
            widget=forms.Select(attrs={
                'class': 'js-select2 select2-username',
            }),
        )
        positive_permissions = PermissionFormField(
            label=_('Permissions'),
            queryset=permission_queryset,
            required=False,
            widget=forms.SelectMultiple(
                attrs={
                    'class': 'js-select2 select2-multiple',
                    'data-placeholder': _('Select one or more permissions'),
                }),
        )

    link = lambda instance: unicode(instance.profile)
    directory_permissions = current_directory.permission_sets \
                                             .order_by('profile').all()

    return util.edit(request,
                     template,
                     PermissionSet,
                     context,
                     link,
                     linkfield='profile',
                     queryset=directory_permissions,
                     can_delete=True,
                     form=PermissionSetForm)
예제 #38
0
파일: views.py 프로젝트: synasius/pootle
def project_admin(request, current_project):
    """adding and deleting project languages"""
    template_translation_project = current_project \
                                        .get_template_translationproject()

    class TranslationProjectForm(forms.ModelForm):

        if template_translation_project is not None:
            update = forms.BooleanField(required=False,
                                        label=_("Update against templates"))

        #FIXME: maybe we can detect if initialize is needed to avoid
        # displaying it when not relevant
        #initialize = forms.BooleanField(required=False, label=_("Initialize"))

        project = forms.ModelChoiceField(
            queryset=Project.objects.filter(pk=current_project.pk),
            initial=current_project.pk,
            widget=forms.HiddenInput)
        language = LiberalModelChoiceField(
            label=_("Language"),
            queryset=Language.objects.exclude(
                translationproject__project=current_project),
            widget=forms.Select(attrs={
                'class': 'js-select2 select2-language',
            }),
        )

        class Meta:
            prefix = "existing_language"
            model = TranslationProject

        def process_extra_fields(self):
            if self.instance.pk is not None:
                if self.cleaned_data.get('initialize', None):
                    self.instance.initialize()

                if (self.cleaned_data.get('update', None)
                        or not self.instance.stores.count()):
                    self.instance.update_against_templates()

    queryset = TranslationProject.objects.filter(
        project=current_project).order_by('pootle_path')

    model_args = {
        'project': {
            'code': current_project.code,
            'name': current_project.fullname,
        }
    }

    link = lambda instance: '<a href="%s">%s</a>' % (
        l(instance.pootle_path + 'admin_permissions.html'),
        instance.language,
    )

    return util.edit(request,
                     'project/project_admin.html',
                     TranslationProject,
                     model_args,
                     link,
                     linkfield="language",
                     queryset=queryset,
                     can_delete=True,
                     form=TranslationProjectForm,
                     formset=TranslationProjectFormSet,
                     exclude=('description', ))
예제 #39
0
def view(request):
    queryset = Language.objects.exclude(code='templates')
    try:
        default_lang = Language.objects.get(code='en')
    except Language.DoesNotExist:
        default_lang = queryset[0]


    class ProjectForm(forms.ModelForm):

        source_language = forms.ModelChoiceField(
            label=_('Source Language'),
            initial=default_lang.pk,
            queryset=queryset,
        )

        class Meta:
            model = Project
            fields = (
                'code', 'fullname', 'checkstyle', 'localfiletype', 'treestyle',
                'source_language', 'screenshot_search_prefix', 'disabled',
            )

        def __init__(self, *args, **kwargs):
            super(ProjectForm, self).__init__(*args, **kwargs)
            if self.instance.id:
                has_stores = Store.objects.filter(
                        translation_project__project=self.instance
                    ).count
                if has_stores:
                    self.fields['localfiletype'].widget.attrs['disabled'] = True
                    self.fields['localfiletype'].required = False
                if (self.instance.treestyle != 'auto' and
                    self.instance.translationproject_set.count() and
                    self.instance.treestyle ==
                        self.instance._detect_treestyle()):
                    self.fields['treestyle'].widget.attrs['disabled'] = True
                    self.fields['treestyle'].required = False
            self.fields['checkstyle'].widget.attrs['class'] = \
                "js-select2 select2-checkstyle"
            self.fields['localfiletype'].widget.attrs['class'] = \
                "js-select2 select2-localfiletype"
            self.fields['treestyle'].widget.attrs['class'] = \
                "js-select2 select2-treestyle"
            self.fields['source_language'].widget.attrs['class'] = \
                "js-select2 select2-language"

        def clean_localfiletype(self):
            value = self.cleaned_data.get('localfiletype', None)
            if not value:
                value = self.instance.localfiletype
            return value

        def clean_treestyle(self):
            value = self.cleaned_data.get('treestyle', None)
            if not value:
                value = self.instance.treestyle
            return value

        def clean_code(self):
            value = self.cleaned_data['code']
            if value in RESERVED_PROJECT_CODES:
                raise ValidationError(_('"%s" cannot be used as a project '
                                        'code' % value))
            return value

    def generate_link(project):
        langs_url = reverse('pootle-project-admin-languages',
                            args=[project.code])
        return '<a href="%s">%s</a>' % (langs_url, project.code)

    return util.edit(
            request,
            'admin/projects.html',
            Project,
            link=generate_link,
            form=ProjectForm,
            can_delete=True,
    )
예제 #40
0
def admin_permissions(request, current_directory, template, ctx):
    language = ctx.get('language', None)

    negative_permissions_excl = list(PERMISSIONS['negative'])
    positive_permissions_excl = list(PERMISSIONS['positive'])

    # Don't provide means to alter access permissions under /<lang_code>/*
    # In other words: only allow setting access permissions for the root
    # and the `/projects/<code>/` directories
    if language is not None:
        access_permissions = ['view', 'hide']
        negative_permissions_excl.extend(access_permissions)
        positive_permissions_excl.extend(access_permissions)

    content_type = get_permission_contenttype()

    positive_permissions_qs = content_type.permission_set.exclude(
        codename__in=negative_permissions_excl, )
    negative_permissions_qs = content_type.permission_set.exclude(
        codename__in=positive_permissions_excl, )

    base_queryset = User.objects.filter(is_active=1).exclude(
        id__in=current_directory.permission_sets.values_list('user_id',
                                                             flat=True), )
    querysets = [(None, base_queryset.filter(username__in=('nobody',
                                                           'default')))]

    querysets.append((
        _('All Users'),
        base_queryset.exclude(username__in=('nobody',
                                            'default')).order_by('username'),
    ))

    class PermissionSetForm(forms.ModelForm):
        class Meta(object):
            model = PermissionSet
            fields = ('user', 'directory', 'positive_permissions',
                      'negative_permissions')

        directory = forms.ModelChoiceField(
            queryset=Directory.objects.filter(pk=current_directory.pk),
            initial=current_directory.pk,
            widget=forms.HiddenInput,
        )
        user = GroupedModelChoiceField(
            label=_('Username'),
            querysets=querysets,
            queryset=User.objects.all(),
            required=True,
            widget=forms.Select(attrs={
                'class': 'js-select2 select2-username',
            }),
        )
        positive_permissions = PermissionFormField(
            label=_('Add Permissions'),
            queryset=positive_permissions_qs,
            required=False,
            widget=forms.SelectMultiple(
                attrs={
                    'class': 'js-select2 select2-multiple',
                    'data-placeholder': _('Select one or more permissions'),
                }),
        )
        negative_permissions = PermissionFormField(
            label=_('Revoke Permissions'),
            queryset=negative_permissions_qs,
            required=False,
            widget=forms.SelectMultiple(
                attrs={
                    'class': 'js-select2 select2-multiple',
                    'data-placeholder': _('Select one or more permissions'),
                }),
        )

        def __init__(self, *args, **kwargs):
            super(PermissionSetForm, self).__init__(*args, **kwargs)

            # Don't display extra negative permissions field where they
            # are not applicable
            if language is not None:
                del self.fields['negative_permissions']

    link = lambda instance: unicode(instance.user)
    directory_permissions = current_directory.permission_sets \
                                             .order_by('user').all()

    return util.edit(request,
                     template,
                     PermissionSet,
                     ctx,
                     link,
                     linkfield='user',
                     queryset=directory_permissions,
                     can_delete=True,
                     form=PermissionSetForm)
예제 #41
0
파일: views.py 프로젝트: AlfredWei/pootle
def manage_store(request, ctx, language, term_store):
    TermUnitForm = term_unit_form_factory(term_store)
    template_name = 'translation_projects/terminology/manage.html'
    return util.edit(request, template_name, Unit, ctx,
                     None, None, queryset=term_store.units, can_delete=True,
                     form=TermUnitForm)
예제 #42
0
파일: permissions.py 프로젝트: sshyran/zing
def admin_permissions(request, current_directory, template, ctx):
    language = ctx.get("language", None)

    negative_permissions_excl = list(PERMISSIONS["negative"])
    positive_permissions_excl = list(PERMISSIONS["positive"])

    # Don't provide means to alter access permissions under /<lang_code>/*
    # In other words: only allow setting access permissions for the root
    # and the `/projects/<code>/` directories
    if language is not None:
        access_permissions = ["view", "hide"]
        negative_permissions_excl.extend(access_permissions)
        positive_permissions_excl.extend(access_permissions)

    content_type = get_permission_contenttype()

    positive_permissions_qs = content_type.permission_set.exclude(
        codename__in=negative_permissions_excl, )
    negative_permissions_qs = content_type.permission_set.exclude(
        codename__in=positive_permissions_excl, )

    base_queryset = User.objects.filter(is_active=1).exclude(
        id__in=current_directory.permission_sets.values_list("user_id",
                                                             flat=True), )
    choice_groups = [
        (None, base_queryset.filter(username__in=("nobody", "default")))
    ]

    choice_groups.append((
        _("All Users"),
        base_queryset.exclude(username__in=("nobody",
                                            "default")).order_by("username"),
    ))

    class PermissionSetForm(forms.ModelForm):
        class Meta(object):
            model = PermissionSet
            fields = (
                "user",
                "directory",
                "positive_permissions",
                "negative_permissions",
            )

        directory = forms.ModelChoiceField(
            queryset=Directory.objects.filter(pk=current_directory.pk),
            initial=current_directory.pk,
            widget=forms.HiddenInput,
        )
        user = GroupedModelChoiceField(
            label=_("Username"),
            choice_groups=choice_groups,
            queryset=User.objects.all(),
            required=True,
            widget=forms.Select(
                attrs={"class": "js-select2 select2-username"}),
        )
        positive_permissions = PermissionFormField(
            label=_("Add Permissions"),
            queryset=positive_permissions_qs,
            required=False,
            widget=forms.SelectMultiple(
                attrs={
                    "class": "js-select2 select2-multiple",
                    "data-placeholder": _("Select one or more permissions"),
                }),
        )
        negative_permissions = PermissionFormField(
            label=_("Revoke Permissions"),
            queryset=negative_permissions_qs,
            required=False,
            widget=forms.SelectMultiple(
                attrs={
                    "class": "js-select2 select2-multiple",
                    "data-placeholder": _("Select one or more permissions"),
                }),
        )

        def __init__(self, *args, **kwargs):
            super(PermissionSetForm, self).__init__(*args, **kwargs)

            # Don't display extra negative permissions field where they
            # are not applicable
            if language is not None:
                del self.fields["negative_permissions"]

    def link(instance):
        return str(instance.user)

    directory_permissions = current_directory.permission_sets.order_by(
        "user").all()

    return util.edit(
        request,
        template,
        PermissionSet,
        ctx,
        link,
        linkfield="user",
        queryset=directory_permissions,
        can_delete=True,
        form=PermissionSetForm,
    )
예제 #43
0
def project_admin(request, project_code):
    """adding and deleting project languages"""
    current_project = Project.objects.get(code=project_code)
    request.permissions = get_matching_permissions(get_profile(request.user),
                                                   current_project.directory)
    if not check_permission('administrate', request):
        raise PermissionDenied(
            _("You do not have rights to administer this project."))

    template_translation_project = current_project.get_template_translationproject(
    )

    class TranslationProjectForm(forms.ModelForm):
        if template_translation_project is not None:
            update = forms.BooleanField(required=False,
                                        label=_("Update from templates"))
        #FIXME: maybe we can detect if initialize is needed to avoid
        # displaying it when not relevant
        #initialize = forms.BooleanField(required=False, label=_("Initialize"))
        project = forms.ModelChoiceField(
            queryset=Project.objects.filter(pk=current_project.pk),
            initial=current_project.pk,
            widget=forms.HiddenInput)
        language = LiberalModelChoiceField(
            label=_("Language"),
            queryset=Language.objects.exclude(
                translationproject__project=current_project))

        class Meta:
            prefix = "existing_language"
            model = TranslationProject

        def process_extra_fields(self):
            if self.instance.pk is not None:
                if self.cleaned_data.get('initialize', None):
                    self.instance.initialize()

                if self.cleaned_data.get(
                        'update', None) or not self.instance.stores.count():
                    self.instance.update_from_templates()

    queryset = TranslationProject.objects.filter(
        project=current_project).order_by('pootle_path')
    model_args = {}
    model_args['project'] = {
        'code': current_project.code,
        'name': current_project.fullname
    }
    model_args['formid'] = "translation-projects"
    model_args['submitname'] = "changetransprojects"
    link = lambda instance: '<a href="%s">%s</a>' % (l(
        instance.pootle_path + 'admin_permissions.html'), instance.language)
    return util.edit(request,
                     'project/project_admin.html',
                     TranslationProject,
                     model_args,
                     link,
                     linkfield="language",
                     queryset=queryset,
                     can_delete=True,
                     form=TranslationProjectForm,
                     formset=TranslationProjectFormSet)
예제 #44
0
def admin_permissions(request, current_directory, template, context):
    User = get_user_model()
    project = context.get('project', None)
    language = context.get('language', None)

    # FIXME: Shouldn't we just remove unused permissions from the DB?
    excluded_permissions = [
        'add_directory', 'change_directory', 'delete_directory',
    ]
    # Don't provide means to add `view` permissions under /<lang_code>/*
    # In other words: only allow setting `view` permissions for the root
    # and the `/projects/<code>/` directories
    if language is not None:
        excluded_permissions.append('view')

    content_type = get_permission_contenttype()
    permission_queryset = content_type.permission_set.exclude(
        codename__in=excluded_permissions,
    )

    excluded = current_directory.permission_sets.values_list("user_id", flat=True)
    base_queryset = User.objects.filter(is_active=True).exclude(excluded)
    querysets = [(None, base_queryset.filter(username__in=("nobody", "default")))]

    if project is not None:
        if language is not None:
            group_label = _('Translation Project Contributors')
            tp_path = '/%s/%s/' % (language.code, project.code)
            contributions = Submission.objects.filter(
                    translation_project__pootle_path=tp_path,
                )
        else:
            group_label = _('Project Contributors')
            contributions = Submission.objects.filter(
                    translation_project__project__code=project.code,
                )

        querysets.append((
            group_label,
            base_queryset.filter(submission__in=contributions)
                         .distinct().order_by("username"),
        ))

    if language is not None:
        contributions = Submission.objects.filter(
                translation_project__language__code=language.code,
            )
        querysets.append((
            _('Language Contributors'),
            base_queryset.filter(submission__in=contributions)
                         .distinct().order_by("username"),
        ))

    querysets.append((
        _('All Users'),
        base_queryset.exclude(username__in=("nobody", "default"))
                     .order_by("username"),
    ))


    class PermissionSetForm(forms.ModelForm):

        class Meta:
            model = PermissionSet

        directory = forms.ModelChoiceField(
                queryset=Directory.objects.filter(pk=current_directory.pk),
                initial=current_directory.pk,
                widget=forms.HiddenInput,
        )
        user = GroupedModelChoiceField(
                label=_('Username'),
                querysets=querysets,
                queryset=User.objects.all(),
                required=True,
                widget=forms.Select(attrs={
                    'class': 'js-select2 select2-username',
                }),
        )
        positive_permissions = PermissionFormField(
                label=_('Permissions'),
                queryset=permission_queryset,
                required=False,
                widget=forms.SelectMultiple(attrs={
                    'class': 'js-select2 select2-multiple',
                    'data-placeholder': _('Select one or more permissions'),
                }),
        )

    link = lambda instance: unicode(instance.user)
    queryset = current_directory.permission_sets.order_by("user").all()

    return util.edit(request, template, PermissionSet, context, link,
                     linkfield="user", queryset=queryset,
                     can_delete=True, form=PermissionSetForm)
예제 #45
0
def admin_permissions(request, current_directory, template, context):
    content_type = get_permission_contenttype()
    permission_queryset = content_type.permission_set.exclude(
            codename__in=[
                'add_directory', 'change_directory', 'delete_directory',
            ],
    )

    project = context.get('project', None)
    language = context.get('language', None)

    base_queryset = PootleProfile.objects.filter(user__is_active=1).exclude(
            id__in=current_directory.permission_sets \
                                    .values_list('profile_id', flat=True),
    )
    querysets = [(None, base_queryset.filter(
        user__username__in=('nobody', 'default')
    ))]

    if project is not None:
        if language is not None:
            group_label = _('Translation Project Contributors')
            tp_path = '/%s/%s/' % (language.code, project.code)
            contributions = Submission.objects.filter(
                    translation_project__pootle_path=tp_path,
                )
        else:
            group_label = _('Project Contributors')
            contributions = Submission.objects.filter(
                    translation_project__project__code=project.code,
                )

        querysets.append((
            group_label,
            base_queryset.filter(submission__in=contributions)
                         .distinct()
                         .order_by('user__username'),
        ))

    if language is not None:
        contributions = Submission.objects.filter(
                translation_project__language__code=language.code,
            )
        querysets.append((
            _('Language Contributors'),
            base_queryset.filter(submission__in=contributions)
                         .distinct()
                         .order_by('user__username'),
        ))

    querysets.append((
        _('All Users'),
        base_queryset.exclude(user__username__in=('nobody', 'default'))
                     .order_by('user__username'),
    ))


    class PermissionSetForm(forms.ModelForm):

        class Meta:
            model = PermissionSet

        directory = forms.ModelChoiceField(
                queryset=Directory.objects.filter(pk=current_directory.pk),
                initial=current_directory.pk,
                widget=forms.HiddenInput,
        )
        profile = GroupedModelChoiceField(
                label=_('Username'),
                querysets=querysets,
                queryset=PootleProfile.objects.all(),
                required=True,
                widget=forms.Select(attrs={
                    'class': 'js-select2 select2-username',
                }),
        )
        positive_permissions = PermissionFormField(
                label=_('Permissions'),
                queryset=permission_queryset,
                required=False,
                widget=forms.SelectMultiple(attrs={
                    'class': 'js-select2 select2-multiple',
                    'data-placeholder': _('Select one or more permissions'),
                }),
        )

    link = lambda instance: unicode(instance.profile)
    directory_permissions = current_directory.permission_sets \
                                             .order_by('profile').all()

    return util.edit(request, template, PermissionSet, context, link,
                     linkfield='profile', queryset=directory_permissions,
                     can_delete=True, form=PermissionSetForm)
예제 #46
0
def project_admin(request, current_project):
    """adding and deleting project languages"""
    template_translation_project = current_project \
                                        .get_template_translationproject()


    class TranslationProjectForm(forms.ModelForm):

        if template_translation_project is not None:
            update = forms.BooleanField(required=False,
                                        label=_("Update against templates"))

        #FIXME: maybe we can detect if initialize is needed to avoid
        # displaying it when not relevant
        #initialize = forms.BooleanField(required=False, label=_("Initialize"))

        project = forms.ModelChoiceField(
                queryset=Project.objects.filter(pk=current_project.pk),
                initial=current_project.pk, widget=forms.HiddenInput
        )
        language = LiberalModelChoiceField(
                label=_("Language"),
                queryset=Language.objects.exclude(
                    translationproject__project=current_project),
                widget=forms.Select(attrs={
                    'class': 'js-select2 select2-language',
                }),
        )

        class Meta:
            prefix = "existing_language"
            model = TranslationProject

        def process_extra_fields(self):
            if self.instance.pk is not None:
                if self.cleaned_data.get('initialize', None):
                    self.instance.initialize()

                if (self.cleaned_data.get('update', None) or
                    not self.instance.stores.count()):
                    self.instance.update_against_templates()

    queryset = TranslationProject.objects.filter(
            project=current_project).order_by('pootle_path')

    model_args = {
        'project': {
            'code': current_project.code,
            'name': current_project.fullname,
        }
    }

    link = lambda instance: '<a href="%s">%s</a>' % (
            l(instance.pootle_path + 'admin_permissions.html'),
            instance.language,
    )

    return util.edit(request, 'project/project_admin.html', TranslationProject,
                     model_args, link, linkfield="language", queryset=queryset,
                     can_delete=True, form=TranslationProjectForm,
                     formset=TranslationProjectFormSet,
                     exclude=('description',))
예제 #47
0
파일: adminusers.py 프로젝트: nielx/pootle
def view(request):
    fields = ("username", "first_name", "last_name", "email", "is_active", "is_superuser")
    queryset = User.objects.hide_defaults().order_by("username")
    return util.edit(
        request, "admin/users.html", User, fields=fields, formset=BaseUserFormSet, queryset=queryset, can_delete=True
    )
예제 #48
0
def admin_permissions(request, current_directory, template, ctx):
    language = ctx.get('language', None)

    negative_permissions_excl = list(PERMISSIONS['negative'])
    positive_permissions_excl = list(PERMISSIONS['positive'])

    # Don't provide means to alter access permissions under /<lang_code>/*
    # In other words: only allow setting access permissions for the root
    # and the `/projects/<code>/` directories
    if language is not None:
        access_permissions = ['view', 'hide']
        negative_permissions_excl.extend(access_permissions)
        positive_permissions_excl.extend(access_permissions)

    content_type = get_permission_contenttype()

    positive_permissions_qs = content_type.permission_set.exclude(
        codename__in=negative_permissions_excl,
    )
    negative_permissions_qs = content_type.permission_set.exclude(
        codename__in=positive_permissions_excl,
    )

    base_queryset = User.objects.filter(is_active=1).exclude(
        id__in=current_directory.permission_sets.values_list('user_id',
                                                             flat=True),)
    querysets = [(None, base_queryset.filter(
        username__in=('nobody', 'default')
    ))]

    querysets.append((
        _('All Users'),
        base_queryset.exclude(username__in=('nobody',
                                            'default')).order_by('username'),
    ))

    class PermissionSetForm(forms.ModelForm):

        class Meta(object):
            model = PermissionSet
            fields = ('user', 'directory', 'positive_permissions',
                      'negative_permissions')

        directory = forms.ModelChoiceField(
            queryset=Directory.objects.filter(pk=current_directory.pk),
            initial=current_directory.pk,
            widget=forms.HiddenInput,
        )
        user = GroupedModelChoiceField(
            label=_('Username'),
            querysets=querysets,
            queryset=User.objects.all(),
            required=True,
            widget=forms.Select(attrs={
                'class': 'js-select2 select2-username',
            }),
        )
        positive_permissions = PermissionFormField(
            label=_('Add Permissions'),
            queryset=positive_permissions_qs,
            required=False,
            widget=forms.SelectMultiple(attrs={
                'class': 'js-select2 select2-multiple',
                'data-placeholder': _('Select one or more permissions'),
            }),
        )
        negative_permissions = PermissionFormField(
            label=_('Revoke Permissions'),
            queryset=negative_permissions_qs,
            required=False,
            widget=forms.SelectMultiple(attrs={
                'class': 'js-select2 select2-multiple',
                'data-placeholder': _('Select one or more permissions'),
            }),
        )

        def __init__(self, *args, **kwargs):
            super(PermissionSetForm, self).__init__(*args, **kwargs)

            # Don't display extra negative permissions field where they
            # are not applicable
            if language is not None:
                del self.fields['negative_permissions']

    link = lambda instance: unicode(instance.user)
    directory_permissions = current_directory.permission_sets \
                                             .order_by('user').all()

    return util.edit(request, template, PermissionSet, ctx, link,
                     linkfield='user', queryset=directory_permissions,
                     can_delete=True, form=PermissionSetForm)