<commit_before>import autocomplete_light
import rules
from django.contrib.auth import get_user_model
from django.contrib import admin
from django.contrib.admin.widgets import AdminRadioSelect
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.forms import (
    HiddenInput,
    NullBooleanSelect,
    ModelForm,
    ValidationError,
    ModelChoiceField,
)
from django.utils.translation import ugettext_lazy as _
from django_extensions.admin import ForeignKeyAutocompleteAdmin
from powerdns.models.powerdns import (
    CryptoKey,
    Domain,
    DomainMetadata,
    Record,
    SuperMaster,
)
from powerdns.models.authorisations import Authorisation
from rules.contrib.admin import ObjectPermissionsModelAdmin
from threadlocals.threadlocals import get_current_user


from powerdns.models.powerdns import can_delete, can_edit
from powerdns.models.templates import (
    DomainTemplate,
    RecordTemplate,
)
from powerdns.models.requests import (
    DeleteRequest,
    DomainRequest,
    RecordRequest,
)
from powerdns.utils import Owned, DomainForRecordValidator, is_owner
from powerdns.models.tsigkeys import TsigKey


class NullBooleanRadioSelect(NullBooleanSelect, AdminRadioSelect):
    pass


try:
    from django.contrib.admin import SimpleListFilter
except ImportError:
    _domain_filters = ('type', 'last_check', 'account',)
else:
    class ReverseDomainListFilter(SimpleListFilter):
        title = _('domain class')

        # Parameter for the filter that will be used in the URL query.
        parameter_name = 'domain_class'

        def lookups(self, request, model_admin):
            return (
                ('fwd', _('domain:forward')),
                ('rev', _('domain:reverse')),
            )

        def queryset(self, request, queryset):
            q = (models.Q(name__endswith='.in-addr.arpa') |
                 models.Q(name__endswith='.ip6.arpa'))
            if self.value() == 'fwd':
                return queryset.exclude(q)
            if self.value() == 'rev':
                return queryset.filter(q)
    _domain_filters = (
        ReverseDomainListFilter, 'type', 'last_check', 'account',
    )


class RecordAdminForm(ModelForm):

    def clean_type(self):
        type = self.cleaned_data['type']
        if not type:
            raise ValidationError(_("Record type is required"))
        return type

    def clean_domain(self):
        if (
            self.instance.pk and
            self.instance.domain == self.cleaned_data['domain']
        ):
            # Domain unchanged. Maybe user was assigned the record in a domain
            # She doesn't own.
            return self.cleaned_data['domain']
        validator = DomainForRecordValidator()
        validator.user = self.user
        return validator(self.cleaned_data['domain'])


class CopyingAdmin(admin.ModelAdmin):

    field_prefix = ''
    target_prefix = ''

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        from_pk = request.GET.get(self.from_field)
        if from_pk is not None:
            self.from_object = self.FromModel.objects.get(pk=from_pk)
            for field in self.CopyFieldsModel.copy_fields:
                form.base_fields[field[len(self.field_prefix):]].initial = \
                    getattr(self.from_object, field[len(self.target_prefix):])
        else:
            self.from_object = None
        return form


class RequestAdmin(CopyingAdmin):
    """Admin for domain/record requests"""

    def get_form(self, *args, **kwargs):
        form = super().get_form(*args, **kwargs)
        form.base_fields['target_owner'].initial =\
            form.base_fields['target_owner'].initial or get_current_user()
        return form


class OwnedAdmin(ForeignKeyAutocompleteAdmin, ObjectPermissionsModelAdmin):
    """Admin for models with owner field"""

    def save_model(self, request, object_, form, change):
        if object_.owner is None:
            object_.owner = request.user
        object_.email_owner(request.user)
        super(OwnedAdmin, self).save_model(request, object_, form, change)

    def get_related_filter(self, model, request):
        return super(OwnedAdmin, self).get_related_filter(model, request)
        user = request.user
        if not issubclass(model, Owned) or rules.is_superuser(user):
            return super(OwnedAdmin, self).get_related_filter(model, request)
        return models.Q(owner=user)


class RecordAdmin(OwnedAdmin, CopyingAdmin):
    def has_delete_permission(self, request, obj=None):
        return can_delete(request.user, obj)<commit_msg>Add search fields to RecordRequest admin (#147)<commit_after>import autocomplete_light
import rules
from django.contrib.auth import get_user_model
from django.contrib import admin
from django.contrib.admin.widgets import AdminRadioSelect
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.forms import (
    HiddenInput,
    NullBooleanSelect,
    ModelForm,
    ValidationError,
    ModelChoiceField,
)
from django.utils.translation import ugettext_lazy as _
from django_extensions.admin import ForeignKeyAutocompleteAdmin
from powerdns.models.powerdns import (
    CryptoKey,
    Domain,
    DomainMetadata,
    Record,
    SuperMaster,
)
from powerdns.models.authorisations import Authorisation
from rules.contrib.admin import ObjectPermissionsModelAdmin
from threadlocals.threadlocals import get_current_user


from powerdns.models.powerdns import can_delete, can_edit
from powerdns.models.templates import (
    DomainTemplate,
    RecordTemplate,
)
from powerdns.models.requests import (
    DeleteRequest,
    DomainRequest,
    RecordRequest,
)
from powerdns.utils import Owned, DomainForRecordValidator, is_owner
from powerdns.models.tsigkeys import TsigKey


class NullBooleanRadioSelect(NullBooleanSelect, AdminRadioSelect):
    pass


try:
    from django.contrib.admin import SimpleListFilter
except ImportError:
    _domain_filters = ('type', 'last_check', 'account',)
else:
    class ReverseDomainListFilter(SimpleListFilter):
        title = _('domain class')

        # Parameter for the filter that will be used in the URL query.
        parameter_name = 'domain_class'

        def lookups(self, request, model_admin):
            return (
                ('fwd', _('domain:forward')),
                ('rev', _('domain:reverse')),
            )

        def queryset(self, request, queryset):
            q = (models.Q(name__endswith='.in-addr.arpa') |
                 models.Q(name__endswith='.ip6.arpa'))
            if self.value() == 'fwd':
                return queryset.exclude(q)
            if self.value() == 'rev':
                return queryset.filter(q)
    _domain_filters = (
        ReverseDomainListFilter, 'type', 'last_check', 'account',
    )


class RecordAdminForm(ModelForm):

    def clean_type(self):
        type = self.cleaned_data['type']
        if not type:
            raise ValidationError(_("Record type is required"))
        return type

    def clean_domain(self):
        if (
            self.instance.pk and
            self.instance.domain == self.cleaned_data['domain']
        ):
            # Domain unchanged. Maybe user was assigned the record in a domain
            # She doesn't own.
            return self.cleaned_data['domain']
        validator = DomainForRecordValidator()
        validator.user = self.user
        return validator(self.cleaned_data['domain'])


class CopyingAdmin(admin.ModelAdmin):

    field_prefix = ''
    target_prefix = ''

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        from_pk = request.GET.get(self.from_field)
        if from_pk is not None:
            self.from_object = self.FromModel.objects.get(pk=from_pk)
            for field in self.CopyFieldsModel.copy_fields:
                form.base_fields[field[len(self.field_prefix):]].initial = \
                    getattr(self.from_object, field[len(self.target_prefix):])
        else:
            self.from_object = None
        return form


class RequestAdmin(CopyingAdmin):
    """Admin for domain/record requests"""

    search_fields = ['target_name', 'key', 'target_content']

    def get_form(self, *args, **kwargs):
        form = super().get_form(*args, **kwargs)
        form.base_fields['target_owner'].initial =\
            form.base_fields['target_owner'].initial or get_current_user()
        return form


class OwnedAdmin(ForeignKeyAutocompleteAdmin, ObjectPermissionsModelAdmin):
    """Admin for models with owner field"""

    def save_model(self, request, object_, form, change):
        if object_.owner is None:
            object_.owner = request.user
        object_.email_owner(request.user)
        super(OwnedAdmin, self).save_model(request, object_, form, change)

    def get_related_filter(self, model, request):
        return super(OwnedAdmin, self).get_related_filter(model, request)
        user = request.user
        if not issubclass(model, Owned) or rules.is_superuser(user):
            return super(OwnedAdmin, self).get_related_filter(model, request)
        return models.Q(owner=user)


class RecordAdmin(OwnedAdmin, CopyingAdmin):
    def has_delete_permission(self, request, obj=None):
        return can_delete(request.user, obj)
{'fraction_non_alphanumeric': 0.09475249628213299, 'fraction_numerical': 0.0005311238580837051, 'mean_word_length': 3.0252244548952545, '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': '5349933', 'n_tokens_mistral': 2687, 'n_tokens_neox': 2594, 'n_words': 629}