<commit_before>from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.conf.urls import url
from django.core.urlresolvers import reverse
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from import_export.admin import ExportMixin
from import_export.formats import base_formats
from import_export.resources import ModelResource
from . import models


class DzSelectFieldListFilter(admin.AllValuesFieldListFilter):
    template = 'admin/dz/list_filter.html'


class DzArchivedListFilter(admin.SimpleListFilter):
    title = _('archive filter')
    parameter_name = 'arch'

    def lookups(self, request, model_admin):
        return [
            ('-', _('All')),        # The "All" choice is not default (None)
            ('a', _('Archived')),
            ('f', _('Fresh')),
        ]

    def choices(self, changelist):
        choices = super(DzArchivedListFilter, self).choices(changelist)
        return list(choices)[1:]   # Skip the All (None) choice

    def queryset(self, request, queryset):
        if self.value() is None or self.value() == 'f':
            return queryset.filter(archived='fresh')  # Filter by "fresh" if default (None)
        if self.value() == 'a':
            return queryset.filter(archived='archived')


class DzModelAdmin(admin.ModelAdmin):
    list_per_page = 50
    actions = None
    can_crawl = can_export = False

    # class Media:
    #     css = {'all': ['dz/admin/changelist.css', 'dz/admin/results.css']}
    #     js = ['dz/admin/filter.js']

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return request.user.is_superuser

    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser

    def changelist_view(self, request, extra_context=None):
        tpl_resp = super(DzModelAdmin, self).changelist_view(request, extra_context)
        tpl_resp.context_data.update({
            'title': _(self.opts.verbose_name_plural.title()),  # override title
            'can_crawl': self.can_crawl,
            'can_export': self.can_export,
        })
        return tpl_resp


class DzCrawlModelAdmin(ExportMixin, DzModelAdmin):
    change_list_template = 'admin/dz/change_list.html'
    formats = [base_formats.XLSX]
    can_crawl = can_export = True

    def get_urls(self):
        urls = super(DzCrawlModelAdmin, self).get_urls()
        my_urls = [url(r'^crawl/$', self.admin_site.admin_view(self.crawl_view),
                       name='%s_%s_crawl' % (self.opts.app_label, self.opts.model_name))]
        return my_urls + urls

    def crawl_view(self, request, extra_context=None):
        opts = self.opts
        if self.can_crawl:
            message = '%s crawling started!' % opts.verbose_name_plural.title()
            self.message_user(request, _(message))
        url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name),
                      current_app=self.admin_site.name)
        url = add_preserved_filters(
            {'preserved_filters': self.get_preserved_filters(request), 'opts': opts}, url)
        return HttpResponseRedirect(url)


class DzExportResource(ModelResource):
    @classmethod
    def field_from_django_field(cls, field_name, django_field, readonly):
        field = super(DzExportResource, cls)\
            .field_from_django_field(field_name, django_field, readonly)
        field.column_name = django_field.verbose_name
        return field


class NewsExportResource(DzExportResource):
    class Meta:<commit_msg>simulate "view only" permission by readonly fields<commit_after>from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.conf.urls import url
from django.core.urlresolvers import reverse
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from import_export.admin import ExportMixin
from import_export.formats import base_formats
from import_export.resources import ModelResource
from . import models


class DzSelectFieldListFilter(admin.AllValuesFieldListFilter):
    template = 'admin/dz/list_filter.html'


class DzArchivedListFilter(admin.SimpleListFilter):
    title = _('archive filter')
    parameter_name = 'arch'

    def lookups(self, request, model_admin):
        return [
            ('-', _('All')),        # The "All" choice is not default (None)
            ('a', _('Archived')),
            ('f', _('Fresh')),
        ]

    def choices(self, changelist):
        choices = super(DzArchivedListFilter, self).choices(changelist)
        return list(choices)[1:]   # Skip the All (None) choice

    def queryset(self, request, queryset):
        if self.value() is None or self.value() == 'f':
            return queryset.filter(archived='fresh')  # Filter by "fresh" if default (None)
        if self.value() == 'a':
            return queryset.filter(archived='archived')


class DzModelAdmin(admin.ModelAdmin):
    list_per_page = 50
    actions = None
    can_crawl = can_export = False
    _get_readonly_fields_called = False

    # class Media:
    #     css = {'all': ['dz/admin/changelist.css', 'dz/admin/results.css']}
    #     js = ['dz/admin/filter.js']

    def has_dz_permissions(self, request, require_admin=True):
        try:
            dz_user = request.user.dz_user
            return dz_user.is_admin or not require_admin
        except (models.User.DoesNotExist, AttributeError):
            return request.user.is_superuser

    def has_module_permission(self, request):
        return self.has_dz_permissions(request, require_admin=False)

    def has_add_permission(self, request):
        return self.has_dz_permissions(request)

    def has_change_permission(self, request, obj=None):
        return self.has_dz_permissions(request)

    def has_delete_permission(self, request, obj=None):
        return self.has_dz_permissions(request)

    def get_readonly_fields(self, request, obj=None):
        if self._get_readonly_fields_called or self.has_dz_permissions(request):
            return super(DzModelAdmin, self).get_readonly_fields(request, obj)
        try:
            self._get_readonly_fields_called = True
            return self.get_fields(request, obj)
        finally:
            self._get_readonly_fields_called = False

    def changelist_view(self, request, extra_context=None):
        tpl_resp = super(DzModelAdmin, self).changelist_view(request, extra_context)
        tpl_resp.context_data.update({
            'title': _(self.opts.verbose_name_plural.title()),  # override title
            'can_crawl': self.can_crawl and self.has_dz_permissions(request),
            'can_export': self.can_export,
        })
        return tpl_resp


class DzCrawlModelAdmin(ExportMixin, DzModelAdmin):
    change_list_template = 'admin/dz/change_list.html'
    formats = [base_formats.XLSX]
    can_crawl = can_export = True

    def has_change_permission(self, request, obj=None):
        return self.has_dz_permissions(request, require_admin=False)

    def get_urls(self):
        urls = super(DzCrawlModelAdmin, self).get_urls()
        my_urls = [url(r'^crawl/$', self.admin_site.admin_view(self.crawl_view),
                       name='%s_%s_crawl' % (self.opts.app_label, self.opts.model_name))]
        return my_urls + urls

    def crawl_view(self, request, extra_context=None):
        opts = self.opts
        if self.can_crawl:
            message = '%s crawling started!' % opts.verbose_name_plural.title()
            self.message_user(request, _(message))
        url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name),
                      current_app=self.admin_site.name)
        url = add_preserved_filters(
            {'preserved_filters': self.get_preserved_filters(request), 'opts': opts}, url)
        return HttpResponseRedirect(url)


class DzExportResource(ModelResource):
    @classmethod
    def field_from_django_field(cls, field_name, django_field, readonly):
        field = super(DzExportResource, cls)\
            .field_from_django_field(field_name, django_field, readonly)
        field.column_name = django_field.verbose_name
        return field


class NewsExportResource(DzExportResource):
    class Meta:
{'fraction_non_alphanumeric': 0.10113543251785087, 'fraction_numerical': 0.0007023293924850755, 'mean_word_length': 3.265601597603595, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '592782', 'n_tokens_mistral': 2638, 'n_tokens_neox': 2564, 'n_words': 542}