<commit_before>'''
Derived from http://djangosnippets.org/snippets/2565/
'''
from django.contrib import admin
from django.db.models.fields import related
from django.forms.widgets import SelectMultiple, HiddenInput
from django.http import HttpResponse
from django.utils.html import escape, escapejs

from metashare.repository.editor.related_widget import RelatedFieldWidgetWrapper
from metashare.repository.editor.widgets import SingleChoiceTypeWidget, \
  MultiChoiceTypeWidget

class RelatedAdminMixin(object):
    '''
    Group the joint logic for the related widget to be used in both
    the ModelAdmin and the Inline subclasses.
    '''
    def hide_hidden_fields(self, db_field, kwargs):
        '''
        Return True if db_field is marked as a hidden field, False otherwise.
        '''
        _hidden_fields = getattr(self, 'hidden_fields', None)
        _hidden_fields = _hidden_fields or []
        if db_field.name in _hidden_fields:
            kwargs['widget'] = HiddenInput()
            kwargs['label'] = ''

    def is_subclassable(self, db_field):
        '''
        Return True if db_field points to a subclassable type, False otherwise.
        '''
        if not db_field.rel:
            return False
        _instance = db_field.rel.to()
        return hasattr(_instance, '__schema_name__') \
              and _instance.__schema_name__ == "SUBCLASSABLE"

    def formfield_for_subclassable(self, db_field, **kwargs):
        kwargs.pop('request', None)
        admin_site = self.admin_site
        if isinstance(db_field, related.ManyToManyField):
            widget = MultiChoiceTypeWidget(db_field.rel, admin_site)
        else:
            widget = SingleChoiceTypeWidget(db_field.rel, admin_site)
        kwargs['widget'] = widget
        formfield = db_field.formfield(**kwargs)
        # Ugly trick from http://ionelmc.wordpress.com/2012/01/19/tweaks-for-making-django-admin-faster/
        # to reuse the same database query result for more than one inline of the same type.
        # We benefit from this for the 'validator' field:
        if db_field.name == 'validator':
            formfield.choices = formfield.choices
        return formfield

    def use_hidden_widget_for_one2one(self, db_field, kwargs):
        ''' OneToOne fields are rendered with a HiddenInput instead a select. '''
        if isinstance(db_field, related.OneToOneField):
            attrs = {'id':'id_{}'.format(db_field.name)}
            if db_field.rel:
                _instance = db_field.rel.to()
                if _instance.id:
                    attrs['value'] = _instance.id
            widget = HiddenInput(attrs=attrs)
            kwargs['widget'] = widget

    def is_related_widget_appropriate(self, kwargs, formfield):
        'Determine whether it is appropriate to use a related-widget'
        if formfield and \
                isinstance(formfield.widget, admin.widgets.RelatedFieldWidgetWrapper) and \
                not isinstance(formfield.widget.widget, SelectMultiple) and \
                not ('widget' in kwargs):
            return True
        return False

    def use_related_widget_where_appropriate(self, db_field, kwargs, formfield):
        if self.is_related_widget_appropriate(kwargs, formfield):
            request = kwargs.pop('request', None)
            related_modeladmin = self.admin_site._registry.get(db_field.rel.to)
            can_change_related = bool(related_modeladmin and 
                related_modeladmin.has_change_permission(request))
            can_delete_related = bool(related_modeladmin and 
                related_modeladmin.has_delete_permission(request))
            widget = RelatedFieldWidgetWrapper.from_contrib_wrapper(formfield.widget, 
                can_change_related, 
                can_delete_related)
            formfield.widget = widget

    def edit_response_close_popup_magic(self, obj):
        '''<commit_msg>Fix for the broken unit tests: the criteria for when to use a related widget needed refinement.<commit_after>'''
Derived from http://djangosnippets.org/snippets/2565/
'''
from django.contrib import admin
from django.db.models.fields import related
from django.forms.widgets import SelectMultiple, HiddenInput
from django.http import HttpResponse
from django.utils.html import escape, escapejs

from metashare.repository.editor.related_widget import RelatedFieldWidgetWrapper
from metashare.repository.editor.widgets import SingleChoiceTypeWidget, \
  MultiChoiceTypeWidget
from selectable.forms.widgets import AutoCompleteSelectMultipleWidget

class RelatedAdminMixin(object):
    '''
    Group the joint logic for the related widget to be used in both
    the ModelAdmin and the Inline subclasses.
    '''
    def hide_hidden_fields(self, db_field, kwargs):
        '''
        Return True if db_field is marked as a hidden field, False otherwise.
        '''
        _hidden_fields = getattr(self, 'hidden_fields', None)
        _hidden_fields = _hidden_fields or []
        if db_field.name in _hidden_fields:
            kwargs['widget'] = HiddenInput()
            kwargs['label'] = ''

    def is_subclassable(self, db_field):
        '''
        Return True if db_field points to a subclassable type, False otherwise.
        '''
        if not db_field.rel:
            return False
        _instance = db_field.rel.to()
        return hasattr(_instance, '__schema_name__') \
              and _instance.__schema_name__ == "SUBCLASSABLE"

    def formfield_for_subclassable(self, db_field, **kwargs):
        kwargs.pop('request', None)
        admin_site = self.admin_site
        if isinstance(db_field, related.ManyToManyField):
            widget = MultiChoiceTypeWidget(db_field.rel, admin_site)
        else:
            widget = SingleChoiceTypeWidget(db_field.rel, admin_site)
        kwargs['widget'] = widget
        formfield = db_field.formfield(**kwargs)
        # Ugly trick from http://ionelmc.wordpress.com/2012/01/19/tweaks-for-making-django-admin-faster/
        # to reuse the same database query result for more than one inline of the same type.
        # We benefit from this for the 'validator' field:
        if db_field.name == 'validator':
            formfield.choices = formfield.choices
        return formfield

    def use_hidden_widget_for_one2one(self, db_field, kwargs):
        ''' OneToOne fields are rendered with a HiddenInput instead a select. '''
        if isinstance(db_field, related.OneToOneField):
            attrs = {'id':'id_{}'.format(db_field.name)}
            if db_field.rel:
                _instance = db_field.rel.to()
                if _instance.id:
                    attrs['value'] = _instance.id
            widget = HiddenInput(attrs=attrs)
            kwargs['widget'] = widget

    def is_related_widget_appropriate(self, kwargs, formfield):
        'Determine whether it is appropriate to use a related-widget'
        if 'widget' in kwargs:
            print 'kwarg widget is: ', kwargs['widget']
        if formfield and \
                isinstance(formfield.widget, admin.widgets.RelatedFieldWidgetWrapper) and \
                not isinstance(formfield.widget.widget, SelectMultiple) and \
                not ('widget' in kwargs and isinstance(kwargs['widget'], AutoCompleteSelectMultipleWidget)):
            return True
        return False

    def use_related_widget_where_appropriate(self, db_field, kwargs, formfield):
        if self.is_related_widget_appropriate(kwargs, formfield):
            request = kwargs.pop('request', None)
            related_modeladmin = self.admin_site._registry.get(db_field.rel.to)
            can_change_related = bool(related_modeladmin and 
                related_modeladmin.has_change_permission(request))
            can_delete_related = bool(related_modeladmin and 
                related_modeladmin.has_delete_permission(request))
            widget = RelatedFieldWidgetWrapper.from_contrib_wrapper(formfield.widget, 
                can_change_related, 
                can_delete_related)
            formfield.widget = widget

    def edit_response_close_popup_magic(self, obj):
        '''
{'fraction_non_alphanumeric': 0.08212441603147283, 'fraction_numerical': 0.003196459306614212, 'mean_word_length': 2.702776513427401, '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': '3096946', 'n_tokens_mistral': 2221, 'n_tokens_neox': 2138, 'n_words': 556}