Python django.db.models.ManyToManyField() Examples

The following are code examples for showing how to use django.db.models.ManyToManyField(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: omni-forms   Author: omni-digital   File: models.py    MIT License 6 votes vote down vote up
def get_required_fields(self, exclude_with_default=True):
        """
        Method to get all required fields for the linked content type model

        :param exclude_with_default: Whether or not to exclude fields with default values
        :type exclude_with_default: bool

        :return: List of required field names
        """
        def filter_field(field):
            if field.blank:
                return False
            elif isinstance(field, models.ManyToManyField):
                return False
            elif exclude_with_default and field.has_default():
                return False
            else:
                return True
        return list(filter(filter_field, self.get_model_fields())) 
Example 2
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 6 votes vote down vote up
def __set__(self, instance, value):
        if not self.related.field.rel.through._meta.auto_created:
            opts = self.related.field.rel.through._meta
            raise AttributeError(
                "Cannot set values on a ManyToManyField which specifies an "
                "intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)
            )

        # Force evaluation of `value` in case it's a queryset whose
        # value could be affected by `manager.clear()`. Refs #19816.
        value = tuple(value)

        manager = self.__get__(instance)
        db = router.db_for_write(manager.through, instance=manager.instance)
        with transaction.atomic(using=db, savepoint=False):
            manager.clear()
            manager.add(*value) 
Example 3
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 6 votes vote down vote up
def __set__(self, instance, value):
        if not self.field.rel.through._meta.auto_created:
            opts = self.field.rel.through._meta
            raise AttributeError(
                "Cannot set values on a ManyToManyField which specifies an "
                "intermediary model.  Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)
            )

        # Force evaluation of `value` in case it's a queryset whose
        # value could be affected by `manager.clear()`. Refs #19816.
        value = tuple(value)

        manager = self.__get__(instance)
        db = router.db_for_write(manager.through, instance=manager.instance)
        with transaction.atomic(using=db, savepoint=False):
            manager.clear()
            manager.add(*value) 
Example 4
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 6 votes vote down vote up
def _check_ignored_options(self, **kwargs):
        warnings = []

        if self.null:
            warnings.append(
                checks.Warning(
                    'null has no effect on ManyToManyField.',
                    hint=None,
                    obj=self,
                    id='fields.W340',
                )
            )

        if len(self._validators) > 0:
            warnings.append(
                checks.Warning(
                    'ManyToManyField does not support validators.',
                    hint=None,
                    obj=self,
                    id='fields.W341',
                )
            )

        return warnings 
Example 5
Project: chattR   Author: patrickstocklin   File: validation.py    GNU General Public License v2.0 6 votes vote down vote up
def validate_list_display(self, cls, model):
        " Validate that list_display only contains fields or usable attributes. "
        if hasattr(cls, 'list_display'):
            check_isseq(cls, 'list_display', cls.list_display)
            for idx, field in enumerate(cls.list_display):
                if not callable(field):
                    if not hasattr(cls, field):
                        if not hasattr(model, field):
                            try:
                                model._meta.get_field(field)
                            except FieldDoesNotExist:
                                raise ImproperlyConfigured(
                                    "%s.list_display[%d], %r is not a callable or "
                                    "an attribute of %r or found in the model %r."
                                    % (cls.__name__, idx, field, cls.__name__, model._meta.object_name)
                                )
                        else:
                            # getattr(model, field) could be an X_RelatedObjectsDescriptor
                            f = fetch_attr(cls, model, "list_display[%d]" % idx, field)
                            if isinstance(f, models.ManyToManyField):
                                raise ImproperlyConfigured(
                                    "'%s.list_display[%d]', '%s' is a ManyToManyField "
                                    "which is not supported."
                                    % (cls.__name__, idx, field)
                                ) 
Example 6
Project: resolwe   Author: genialis   File: builder.py    Apache License 2.0 6 votes vote down vote up
def _connect_signal(self, index):
        """Create signals for building indexes."""
        post_save_signal = ElasticSignal(index, 'build')
        post_save_signal.connect(post_save, sender=index.object_type)
        self.signals.append(post_save_signal)

        post_delete_signal = ElasticSignal(index, 'remove_object')
        post_delete_signal.connect(post_delete, sender=index.object_type)
        self.signals.append(post_delete_signal)

        # Connect signals for all dependencies.
        for dependency in index.get_dependencies():
            # Automatically convert m2m fields to dependencies.
            if isinstance(dependency, (models.ManyToManyField, ManyToManyDescriptor)):
                dependency = ManyToManyDependency(dependency)
            elif isinstance(dependency, ReverseManyToOneDescriptor):
                dependency = ReverseManyToOneDependency(dependency)
            elif isinstance(dependency, ForwardManyToOneDescriptor):
                dependency = ForwardManyToOneDependency(dependency)
            elif not isinstance(dependency, Dependency):
                raise TypeError("Unsupported dependency type: {}".format(repr(dependency)))

            signal = dependency.connect(index)
            self.signals.extend(signal) 
Example 7
Project: django-idcops   Author: Wenvki   File: models.py    Apache License 2.0 6 votes vote down vote up
def _dict(self):
        exclude = ['operator_id', 'creator_id', 'created', 'modified']
        opts = self._meta
        data = {}
        keys = [f.attname for f in opts.fields]
        for f in chain(opts.many_to_many):
            #if isinstance(f, models.ManyToManyField):
            if self.pk is None:
                data[f.name] = []
            else:
                data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True))
        original = { k:self.__dict__.get(k) for k in keys if k not in exclude }
        data.update(**original)
        for key, value in data.items():
            if isinstance(value, timezone.datetime):
                value = formats.localize(timezone.template_localtime(value))
            data.update(**{key: value})
        return data 
Example 8
Project: TESTGIT   Author: B-ROY   File: options.py    Apache License 2.0 6 votes vote down vote up
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        """
        Get a form Field for a ManyToManyField.
        """
        # If it uses an intermediary model that isn't auto created, don't show
        # a field in admin.
        if not db_field.rel.through._meta.auto_created:
            return None
        db = kwargs.get('using')

        if db_field.name in self.raw_id_fields:
            kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel,
                                    self.admin_site, using=db)
            kwargs['help_text'] = ''
        elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
            kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))

        queryset = self.get_field_queryset(db, db_field, request)
        if queryset is not None:
            kwargs['queryset'] = queryset

        return db_field.formfield(**kwargs) 
Example 9
Project: TESTGIT   Author: B-ROY   File: validation.py    Apache License 2.0 6 votes vote down vote up
def validate_prepopulated_fields(self, cls, model):
        " Validate that prepopulated_fields if a dictionary  containing allowed field types. "
        # prepopulated_fields
        if hasattr(cls, 'prepopulated_fields'):
            check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields)
            for field, val in cls.prepopulated_fields.items():
                f = get_field(cls, model, 'prepopulated_fields', field)
                if isinstance(f, (models.DateTimeField, models.ForeignKey,
                    models.ManyToManyField)):
                    raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' "
                            "is either a DateTimeField, ForeignKey or "
                            "ManyToManyField. This isn't allowed."
                            % (cls.__name__, field))
                check_isseq(cls, "prepopulated_fields['%s']" % field, val)
                for idx, f in enumerate(val):
                    get_field(cls, model, "prepopulated_fields['%s'][%d]" % (field, idx), f) 
Example 10
Project: TESTGIT   Author: B-ROY   File: validation.py    Apache License 2.0 6 votes vote down vote up
def validate_list_display(self, cls, model):
        " Validate that list_display only contains fields or usable attributes. "
        if hasattr(cls, 'list_display'):
            check_isseq(cls, 'list_display', cls.list_display)
            for idx, field in enumerate(cls.list_display):
                if not callable(field):
                    if not hasattr(cls, field):
                        if not hasattr(model, field):
                            try:
                                model._meta.get_field(field)
                            except models.FieldDoesNotExist:
                                raise ImproperlyConfigured("%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r."
                                    % (cls.__name__, idx, field, cls.__name__, model._meta.object_name))
                        else:
                            # getattr(model, field) could be an X_RelatedObjectsDescriptor
                            f = fetch_attr(cls, model, "list_display[%d]" % idx, field)
                            if isinstance(f, models.ManyToManyField):
                                raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported."
                                    % (cls.__name__, idx, field)) 
Example 11
Project: TESTGIT   Author: B-ROY   File: managers.py    Apache License 2.0 6 votes vote down vote up
def _validate_field_name(self):
        field_names = self.model._meta.get_all_field_names()
        
        # If a custom name is provided, make sure the field exists on the model
        if self.__field_name is not None and self.__field_name not in field_names:
            raise ValueError("%s couldn't find a field named %s in %s." % \
                (self.__class__.__name__, self.__field_name, self.model._meta.object_name))
        
        # Otherwise, see if there is a field called either 'site' or 'sites'
        else:
            for potential_name in ['site', 'sites']:
                if potential_name in field_names:
                    self.__field_name = potential_name
                    self.__is_validated = True
                    break
        
        # Now do a type check on the field (FK or M2M only)
        try:
            field = self.model._meta.get_field(self.__field_name)
            if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
                raise TypeError("%s must be a ForeignKey or ManyToManyField." %self.__field_name)
        except FieldDoesNotExist:
            raise ValueError("%s couldn't find a field named %s in %s." % \
                    (self.__class__.__name__, self.__field_name, self.model._meta.object_name))
        self.__is_validated = True 
Example 12
Project: AneMo   Author: jspargo   File: related.py    GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, to, db_constraint=True, swappable=True, **kwargs):
        try:
            to._meta
        except AttributeError:  # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
            assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
            # Class names must be ASCII in Python 2.x, so we forcibly coerce it here to break early if there's a problem.
            to = str(to)

        kwargs['verbose_name'] = kwargs.get('verbose_name', None)
        kwargs['rel'] = ManyToManyRel(to,
            related_name=kwargs.pop('related_name', None),
            related_query_name=kwargs.pop('related_query_name', None),
            limit_choices_to=kwargs.pop('limit_choices_to', None),
            symmetrical=kwargs.pop('symmetrical', to == RECURSIVE_RELATIONSHIP_CONSTANT),
            through=kwargs.pop('through', None),
            through_fields=kwargs.pop('through_fields', None),
            db_constraint=db_constraint,
        )

        self.swappable = swappable
        self.db_table = kwargs.pop('db_table', None)
        if kwargs['rel'].through is not None:
            assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used."

        super(ManyToManyField, self).__init__(**kwargs) 
Example 13
Project: AneMo   Author: jspargo   File: checks.py    GNU General Public License v2.0 6 votes vote down vote up
def _check_raw_id_fields_item(self, cls, model, field_name, label):
        """ Check an item of `raw_id_fields`, i.e. check that field named
        `field_name` exists in model `model` and is a ForeignKey or a
        ManyToManyField. """

        try:
            field = model._meta.get_field(field_name)
        except models.FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=cls, id='admin.E002')
        else:
            if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
                return must_be('a ForeignKey or ManyToManyField',
                               option=label, obj=cls, id='admin.E003')
            else:
                return [] 
Example 14
Project: xadmin_bugfix   Author: vip68   File: edit.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        # If it uses an intermediary model that isn't auto created, don't show
        # a field in admin.
        if isinstance(db_field, models.ManyToManyField) and not db_field.remote_field.through._meta.auto_created:
            return None

        attrs = self.get_field_attrs(db_field, **kwargs)
        return db_field.formfield(**dict(attrs, **kwargs)) 
Example 15
Project: xadmin_bugfix   Author: vip68   File: edit.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_field_style(self, db_field, style, **kwargs):
        if style in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
            attrs = {'widget': widgets.AdminRadioSelect(
                attrs={'inline': 'inline' if style == 'radio-inline' else ''})}
            if db_field.choices:
                attrs['choices'] = db_field.get_choices(
                    include_blank=db_field.blank,
                    blank_choice=[('', _('Null'))]
                )
            return attrs

        if style in ('checkbox', 'checkbox-inline') and isinstance(db_field, models.ManyToManyField):
            return {'widget': widgets.AdminCheckboxSelect(attrs={'inline': style == 'checkbox-inline'}),
                    'help_text': None} 
Example 16
Project: xadmin_bugfix   Author: vip68   File: edit.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_form_datas(self):
        # Prepare the dict of initial data from the request.
        # We have to special-case M2Ms as a list of comma-separated PKs.
        if self.request_method == 'get':
            initial = dict(self.request.GET.items())
            for k in initial:
                try:
                    f = self.opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            return {'initial': initial}
        else:
            return {'data': self.request.POST, 'files': self.request.FILES} 
Example 17
Project: xadmin_bugfix   Author: vip68   File: multiselect.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        if style == 'm2m_transfer' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleTransfer(db_field.verbose_name, False), 'help_text': ''}
        if style == 'm2m_dropdown' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleDropdown, 'help_text': ''}
        return attrs 
Example 18
Project: xadmin_bugfix   Author: vip68   File: quickform.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def formfield_for_dbfield(self, formfield, db_field, **kwargs):
        if formfield and self.model in self.admin_site._registry and isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
            rel_model = get_model_from_relation(db_field)
            if rel_model in self.admin_site._registry and self.has_model_perm(rel_model, 'add'):
                add_url = self.get_model_url(rel_model, 'add')
                formfield.widget = RelatedFieldWidgetWrapper(
                    formfield.widget, db_field.remote_field, add_url, self.get_model_url(self.model, 'add'))
        return formfield 
Example 19
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        # If it uses an intermediary model that isn't auto created, don't show
        # a field in admin.
        if isinstance(db_field, models.ManyToManyField) and not db_field.rel.through._meta.auto_created:
            return None

        attrs = self.get_field_attrs(db_field, **kwargs)
        return db_field.formfield(**dict(attrs, **kwargs)) 
Example 20
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def get_field_style(self, db_field, style, **kwargs):
        if style in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
            attrs = {'widget': widgets.AdminRadioSelect(
                attrs={'inline': 'inline' if style == 'radio-inline' else ''})}
            if db_field.choices:
                attrs['choices'] = db_field.get_choices(
                    include_blank=db_field.blank,
                    blank_choice=[('', _('Null'))]
                )
            return attrs

        if style in ('checkbox', 'checkbox-inline') and isinstance(db_field, models.ManyToManyField):
            return {'widget': widgets.AdminCheckboxSelect(attrs={'inline': style == 'checkbox-inline'}),
                    'help_text': None} 
Example 21
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def get_form_datas(self):
        # Prepare the dict of initial data from the request.
        # We have to special-case M2Ms as a list of comma-separated PKs.
        if self.request_method == 'get':
            initial = dict(self.request.GET.items())
            for k in initial:
                try:
                    f = self.opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            return {'initial': initial}
        else:
            return {'data': self.request.POST, 'files': self.request.FILES} 
Example 22
Project: django-xadmin   Author: MarkHoo   File: multiselect.py    MIT License 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        if style == 'm2m_transfer' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleTransfer(db_field.verbose_name, False), 'help_text': ''}
        if style == 'm2m_dropdown' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleDropdown, 'help_text': ''}
        return attrs 
Example 23
Project: django-xadmin   Author: MarkHoo   File: quickform.py    MIT License 5 votes vote down vote up
def formfield_for_dbfield(self, formfield, db_field, **kwargs):
        if formfield and self.model in self.admin_site._registry and isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
            rel_model = get_model_from_relation(db_field)
            if rel_model in self.admin_site._registry and self.has_model_perm(rel_model, 'add'):
                add_url = self.get_model_url(rel_model, 'add')
                formfield.widget = RelatedFieldWidgetWrapper(
                    formfield.widget, db_field.rel, add_url, self.get_model_url(self.model, 'add'))
        return formfield 
Example 24
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def get_field_style(self, db_field, style, **kwargs):
        if style in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
            attrs = {'widget': widgets.AdminRadioSelect(
                attrs={'inline': 'inline' if style == 'radio-inline' else ''})}
            if db_field.choices:
                attrs['choices'] = db_field.get_choices(
                    include_blank=db_field.blank,
                    blank_choice=[('', _('Null'))]
                )
            return attrs

        if style in ('checkbox', 'checkbox-inline') and isinstance(db_field, models.ManyToManyField):
            return {'widget': widgets.AdminCheckboxSelect(attrs={'inline': style == 'checkbox-inline'}),
                    'help_text': None} 
Example 25
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def get_form_datas(self):
        # Prepare the dict of initial data from the request.
        # We have to special-case M2Ms as a list of comma-separated PKs.
        if self.request_method == 'get':
            initial = dict(self.request.GET.items())
            for k in initial:
                try:
                    f = self.opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            return {'initial': initial}
        else:
            return {'data': self.request.POST, 'files': self.request.FILES} 
Example 26
Project: django-xadmin   Author: MarkHoo   File: multiselect.py    MIT License 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        if style == 'm2m_transfer' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleTransfer(db_field.verbose_name, False), 'help_text': ''}
        if style == 'm2m_dropdown' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleDropdown, 'help_text': ''}
        return attrs 
Example 27
Project: django-xadmin   Author: MarkHoo   File: quickform.py    MIT License 5 votes vote down vote up
def formfield_for_dbfield(self, formfield, db_field, **kwargs):
        if formfield and self.model in self.admin_site._registry and isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
            rel_model = get_model_from_relation(db_field)
            if rel_model in self.admin_site._registry and self.has_model_perm(rel_model, 'add'):
                add_url = self.get_model_url(rel_model, 'add')
                formfield.widget = RelatedFieldWidgetWrapper(
                    formfield.widget, db_field.rel, add_url, self.get_model_url(self.model, 'add'))
        return formfield 
Example 28
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        # If it uses an intermediary model that isn't auto created, don't show
        # a field in admin.
        if isinstance(db_field, models.ManyToManyField) and not db_field.remote_field.through._meta.auto_created:
            return None

        attrs = self.get_field_attrs(db_field, **kwargs)
        return db_field.formfield(**dict(attrs, **kwargs)) 
Example 29
Project: django-xadmin   Author: MarkHoo   File: edit.py    MIT License 5 votes vote down vote up
def get_form_datas(self):
        # Prepare the dict of initial data from the request.
        # We have to special-case M2Ms as a list of comma-separated PKs.
        if self.request_method == 'get':
            initial = dict(self.request.GET.items())
            for k in initial:
                try:
                    f = self.opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            return {'initial': initial}
        else:
            return {'data': self.request.POST, 'files': self.request.FILES} 
Example 30
Project: django-xadmin   Author: MarkHoo   File: multiselect.py    MIT License 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        if style == 'm2m_transfer' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleTransfer(db_field.verbose_name, False), 'help_text': ''}
        if style == 'm2m_dropdown' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleDropdown, 'help_text': ''}
        return attrs 
Example 31
Project: django-xadmin   Author: MarkHoo   File: quickform.py    MIT License 5 votes vote down vote up
def formfield_for_dbfield(self, formfield, db_field, **kwargs):
        if formfield and self.model in self.admin_site._registry and isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
            rel_model = get_model_from_relation(db_field)
            if rel_model in self.admin_site._registry and self.has_model_perm(rel_model, 'add'):
                add_url = self.get_model_url(rel_model, 'add')
                formfield.widget = RelatedFieldWidgetWrapper(
                    formfield.widget, db_field.remote_field, add_url, self.get_model_url(self.model, 'add'))
        return formfield 
Example 32
Project: omni-forms   Author: omni-digital   File: models.py    MIT License 5 votes vote down vote up
def get_concrete_class_for_model_field(cls, model_field):
        """
        Method for getting a concrete model class to represent the type of form field required

        :param model_field: Model Field instance
        :return: OmniField subclass
        """
        field_mapping = {
            models.CharField: OmniCharField,
            models.TextField: OmniCharField,
            models.BooleanField: OmniBooleanField,
            models.NullBooleanField: OmniBooleanField,
            models.DateField: OmniDateField,
            models.DateTimeField: OmniDateTimeField,
            models.DecimalField: OmniDecimalField,
            models.EmailField: OmniEmailField,
            models.FloatField: OmniFloatField,
            models.IntegerField: OmniIntegerField,
            models.BigIntegerField: OmniIntegerField,
            models.PositiveIntegerField: OmniIntegerField,
            models.PositiveSmallIntegerField: OmniIntegerField,
            models.SmallIntegerField: OmniIntegerField,
            models.CommaSeparatedIntegerField: OmniCharField,
            models.TimeField: OmniTimeField,
            models.URLField: OmniUrlField,
            models.ForeignKey: OmniForeignKeyField,
            models.ManyToManyField: OmniManyToManyField,
            models.SlugField: OmniSlugField,
            models.FileField: OmniFileField,
            models.ImageField: OmniImageField,
            models.DurationField: OmniDurationField,
            models.GenericIPAddressField: OmniGenericIPAddressField
        }
        field_mapping.update(cls.get_custom_field_mapping())
        return field_mapping.get(model_field.__class__) 
Example 33
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_get_concrete_class_for_model_field(self):
        """
        The get_concrete_class_for_model_field method should return the correct OmniField subclass
        """
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.CharField()), OmniCharField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.NullBooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DateTimeField()), OmniDateTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DecimalField()), OmniDecimalField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.EmailField()), OmniEmailField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FloatField()), OmniFloatField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.IntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BigIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.PositiveIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SmallIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.TimeField()), OmniTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.URLField()), OmniUrlField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SlugField()), OmniSlugField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FileField()), OmniFileField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.ImageField()), OmniImageField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DurationField()), OmniDurationField)
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.GenericIPAddressField()),
            OmniGenericIPAddressField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.CommaSeparatedIntegerField()),
            OmniCharField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.PositiveSmallIntegerField()),
            OmniIntegerField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ForeignKey(DummyModel2)),
            OmniForeignKeyField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ManyToManyField(DummyModel2)),
            OmniManyToManyField
        ) 
Example 34
Project: openhatch   Author: campbe13   File: models.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def save_and_check_for_duplicates(self):
        # FIXME: Cache summaries in the DB so this query is faster.
        duplicates = [citation for citation in
                      Citation.objects.filter(
                          portfolio_entry=self.portfolio_entry)
                      if (citation.pk != self.pk) and (citation.summary == self.summary)]

        if duplicates:
            self.ignored_due_to_duplicate = True
        return self.save()

    # [0]: FIXME: Let's learn how to use Django's ManyToManyField etc. 
Example 35
Project: djing   Author: nerosketch   File: migrate2v2_dump.py    The Unlicense 5 votes vote down vote up
def _field_val(self, obj, field):
        # choice fields
        if field.name in self._choice_list_map.keys():
            val = getattr(obj, field.name)
            return self._choice_list_map[field.name].get(val)

        # bit fields
        elif isinstance(field, BitField):
            val = getattr(obj, field.name)
            # val is instance of BitHandler
            return int(val)

        # image fields
        elif isinstance(field, ImageField):
            val = getattr(obj, field.name)
            return getattr(val, 'url') if val else None

        # mac address validated by netaddr.EUI
        elif isinstance(field, MACAddressField):
            val = getattr(obj, field.name)
            return str(val)

        # related fields
        if field.is_relation:
            if isinstance(field, ManyToOneRel):
                return getattr(obj, field.field_name)
            val = getattr(obj, field.attname)
            if isinstance(field, ManyToManyField):
                s = val.only('pk').values_list('pk', flat=True)
                return tuple(s)
            return val

        # all other simple fields
        else:
            v = getattr(obj, field.name)
            if isinstance(v, bool):
                return v
            if field.null:
                return v or None
            return v 
Example 36
Project: chattR   Author: patrickstocklin   File: autodetector.py    GNU General Public License v2.0 5 votes vote down vote up
def _generate_added_field(self, app_label, model_name, field_name):
        field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
        # Fields that are foreignkeys/m2ms depend on stuff
        dependencies = []
        if field.rel and field.rel.to:
            # Account for FKs to swappable models
            swappable_setting = getattr(field, 'swappable_setting', None)
            if swappable_setting is not None:
                dep_app_label = "__setting__"
                dep_object_name = swappable_setting
            else:
                dep_app_label = field.rel.to._meta.app_label
                dep_object_name = field.rel.to._meta.object_name
            dependencies = [(dep_app_label, dep_object_name, None, True)]
            if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
                dependencies.append((
                    field.rel.through._meta.app_label,
                    field.rel.through._meta.object_name,
                    None,
                    True,
                ))
        # You can't just add NOT NULL fields with no default or fields
        # which don't allow empty strings as default.
        preserve_default = True
        if (not field.null and not field.has_default() and
                not isinstance(field, models.ManyToManyField) and
                not (field.blank and field.empty_strings_allowed)):
            field = field.clone()
            field.default = self.questioner.ask_not_null_addition(field_name, model_name)
            preserve_default = False
        self.add_operation(
            app_label,
            operations.AddField(
                model_name=model_name,
                name=field_name,
                field=field,
                preserve_default=preserve_default,
            ),
            dependencies=dependencies,
        ) 
Example 37
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, to, db_constraint=True, swappable=True, **kwargs):
        try:
            to._meta
        except AttributeError:  # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
            assert isinstance(to, six.string_types), (
                "%s(%r) is invalid. First parameter to ManyToManyField must be "
                "either a model, a model name, or the string %r" %
                (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
            )
            # Class names must be ASCII in Python 2.x, so we forcibly coerce it
            # here to break early if there's a problem.
            to = str(to)
        kwargs['verbose_name'] = kwargs.get('verbose_name', None)
        kwargs['rel'] = ManyToManyRel(
            self, to,
            related_name=kwargs.pop('related_name', None),
            related_query_name=kwargs.pop('related_query_name', None),
            limit_choices_to=kwargs.pop('limit_choices_to', None),
            symmetrical=kwargs.pop('symmetrical', to == RECURSIVE_RELATIONSHIP_CONSTANT),
            through=kwargs.pop('through', None),
            through_fields=kwargs.pop('through_fields', None),
            db_constraint=db_constraint,
        )

        self.swappable = swappable
        self.db_table = kwargs.pop('db_table', None)
        if kwargs['rel'].through is not None:
            assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used."

        super(ManyToManyField, self).__init__(**kwargs) 
Example 38
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(ManyToManyField, self).deconstruct()
        # Handle the simpler arguments
        if self.db_table is not None:
            kwargs['db_table'] = self.db_table
        if self.rel.db_constraint is not True:
            kwargs['db_constraint'] = self.rel.db_constraint
        if self.rel.related_name is not None:
            kwargs['related_name'] = self.rel.related_name
        if self.rel.related_query_name is not None:
            kwargs['related_query_name'] = self.rel.related_query_name
        # Rel needs more work.
        if isinstance(self.rel.to, six.string_types):
            kwargs['to'] = self.rel.to
        else:
            kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name)
        if getattr(self.rel, 'through', None) is not None:
            if isinstance(self.rel.through, six.string_types):
                kwargs['through'] = self.rel.through
            elif not self.rel.through._meta.auto_created:
                kwargs['through'] = "%s.%s" % (self.rel.through._meta.app_label, self.rel.through._meta.object_name)
        # If swappable is True, then see if we're actually pointing to the target
        # of a swap.
        swappable_setting = self.swappable_setting
        if swappable_setting is not None:
            # If it's already a settings reference, error
            if hasattr(kwargs['to'], "setting_name"):
                if kwargs['to'].setting_name != swappable_setting:
                    raise ValueError(
                        "Cannot deconstruct a ManyToManyField pointing to a "
                        "model that is swapped in place of more than one model "
                        "(%s and %s)" % (kwargs['to'].setting_name, swappable_setting)
                    )
            # Set it
            from django.db.migrations.writer import SettingsReference
            kwargs['to'] = SettingsReference(
                kwargs['to'],
                swappable_setting,
            )
        return name, path, args, kwargs 
Example 39
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def contribute_to_class(self, cls, name, **kwargs):
        # To support multiple relations to self, it's useful to have a non-None
        # related name on symmetrical relations for internal reasons. The
        # concept doesn't make a lot of sense externally ("you want me to
        # specify *what* on my non-reversible relation?!"), so we set it up
        # automatically. The funky name reduces the chance of an accidental
        # clash.
        if self.rel.symmetrical and (self.rel.to == "self" or self.rel.to == cls._meta.object_name):
            self.rel.related_name = "%s_rel_+" % name

        super(ManyToManyField, self).contribute_to_class(cls, name, **kwargs)

        # The intermediate m2m model is not auto created if:
        #  1) There is a manually specified intermediate, or
        #  2) The class owning the m2m field is abstract.
        #  3) The class owning the m2m field has been swapped out.
        if not self.rel.through and not cls._meta.abstract and not cls._meta.swapped:
            self.rel.through = create_many_to_many_intermediary_model(self, cls)

        # Add the descriptor for the m2m relation
        setattr(cls, self.name, ReverseManyRelatedObjectsDescriptor(self))

        # Set up the accessor for the m2m table name for the relation
        self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta)

        # Populate some necessary rel arguments so that cross-app relations
        # work correctly.
        if isinstance(self.rel.through, six.string_types):
            def resolve_through_model(field, model, cls):
                field.rel.through = model
            add_lazy_relation(cls, self, self.rel.through, resolve_through_model) 
Example 40
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def db_type(self, connection):
        # A ManyToManyField is not represented by a single column,
        # so return None.
        return None 
Example 41
Project: chattR   Author: patrickstocklin   File: checks.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_field_spec_item(self, cls, model, field_name, label):
        if field_name in cls.readonly_fields:
            # Stuff can be put in fields that isn't actually a model field if
            # it's in readonly_fields, readonly_fields will handle the
            # validation of such things.
            return []
        else:
            try:
                field = model._meta.get_field(field_name)
            except FieldDoesNotExist:
                # If we can't find a field on the model that matches, it could
                # be an extra field on the form.
                return []
            else:
                if (isinstance(field, models.ManyToManyField) and
                        not field.rel.through._meta.auto_created):
                    return [
                        checks.Error(
                            ("The value of '%s' cannot include the ManyToManyField '%s', "
                             "because that field manually specifies a relationship model.")
                            % (label, field_name),
                            hint=None,
                            obj=cls,
                            id='admin.E013',
                        )
                    ]
                else:
                    return [] 
Example 42
Project: chattR   Author: patrickstocklin   File: checks.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_filter_item(self, cls, model, field_name, label):
        """ Check one item of `filter_vertical` or `filter_horizontal`, i.e.
        check that given field exists and is a ManyToManyField. """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=cls, id='admin.E019')
        else:
            if not isinstance(field, models.ManyToManyField):
                return must_be('a ManyToManyField', option=label, obj=cls, id='admin.E020')
            else:
                return [] 
Example 43
Project: chattR   Author: patrickstocklin   File: checks.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_prepopulated_fields_key(self, cls, model, field_name, label):
        """ Check a key of `prepopulated_fields` dictionary, i.e. check that it
        is a name of existing field and the field is one of the allowed types.
        """

        forbidden_field_types = (
            models.DateTimeField,
            models.ForeignKey,
            models.ManyToManyField
        )

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=cls, id='admin.E027')
        else:
            if isinstance(field, forbidden_field_types):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which must not be a DateTimeField, "
                        "ForeignKey or ManyToManyField." % (
                            label, field_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E028',
                    )
                ]
            else:
                return [] 
Example 44
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def get_changeform_initial_data(self, request):
        """
        Get the initial form data.
        Unless overridden, this populates from the GET params.
        """
        initial = dict(request.GET.items())
        for k in initial:
            try:
                f = self.model._meta.get_field(k)
            except FieldDoesNotExist:
                continue
            # We have to special-case M2Ms as a list of comma-separated PKs.
            if isinstance(f, models.ManyToManyField):
                initial[k] = initial[k].split(",")
        return initial 
Example 45
Project: chattR   Author: patrickstocklin   File: validation.py    GNU General Public License v2.0 5 votes vote down vote up
def check_field_spec(self, cls, model, flds, label):
        """
        Validate the fields specification in `flds` from a ModelAdmin subclass
        `cls` for the `model` model. Use `label` for reporting problems to the user.

        The fields specification can be a ``fields`` option or a ``fields``
        sub-option from a ``fieldsets`` option component.
        """
        for fields in flds:
            # The entry in fields might be a tuple. If it is a standalone
            # field, make it into a tuple to make processing easier.
            if type(fields) != tuple:
                fields = (fields,)
            for field in fields:
                if field in cls.readonly_fields:
                    # Stuff can be put in fields that isn't actually a
                    # model field if it's in readonly_fields,
                    # readonly_fields will handle the validation of such
                    # things.
                    continue
                try:
                    f = model._meta.get_field(field)
                except FieldDoesNotExist:
                    # If we can't find a field on the model that matches, it could be an
                    # extra field on the form; nothing to check so move on to the next field.
                    continue
                if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created:
                    raise ImproperlyConfigured("'%s.%s' "
                        "can't include the ManyToManyField field '%s' because "
                        "'%s' manually specifies a 'through' model." % (
                            cls.__name__, label, field, field)) 
Example 46
Project: chattR   Author: patrickstocklin   File: validation.py    GNU General Public License v2.0 5 votes vote down vote up
def validate_raw_id_fields(self, cls, model):
        " Validate that raw_id_fields only contains field names that are listed on the model. "
        if hasattr(cls, 'raw_id_fields'):
            check_isseq(cls, 'raw_id_fields', cls.raw_id_fields)
            for idx, field in enumerate(cls.raw_id_fields):
                f = get_field(cls, model, 'raw_id_fields', field)
                if not isinstance(f, (models.ForeignKey, models.ManyToManyField)):
                    raise ImproperlyConfigured("'%s.raw_id_fields[%d]', '%s' must "
                            "be either a ForeignKey or ManyToManyField."
                            % (cls.__name__, idx, field)) 
Example 47
Project: chattR   Author: patrickstocklin   File: validation.py    GNU General Public License v2.0 5 votes vote down vote up
def validate_filter_vertical(self, cls, model):
        " Validate that filter_vertical is a sequence of field names. "
        if hasattr(cls, 'filter_vertical'):
            check_isseq(cls, 'filter_vertical', cls.filter_vertical)
            for idx, field in enumerate(cls.filter_vertical):
                f = get_field(cls, model, 'filter_vertical', field)
                if not isinstance(f, models.ManyToManyField):
                    raise ImproperlyConfigured("'%s.filter_vertical[%d]' must be "
                        "a ManyToManyField." % (cls.__name__, idx)) 
Example 48
Project: chattR   Author: patrickstocklin   File: validation.py    GNU General Public License v2.0 5 votes vote down vote up
def validate_filter_horizontal(self, cls, model):
        " Validate that filter_horizontal is a sequence of field names. "
        if hasattr(cls, 'filter_horizontal'):
            check_isseq(cls, 'filter_horizontal', cls.filter_horizontal)
            for idx, field in enumerate(cls.filter_horizontal):
                f = get_field(cls, model, 'filter_horizontal', field)
                if not isinstance(f, models.ManyToManyField):
                    raise ImproperlyConfigured("'%s.filter_horizontal[%d]' must be "
                        "a ManyToManyField." % (cls.__name__, idx)) 
Example 49
Project: chattR   Author: patrickstocklin   File: custom_user.py    GNU General Public License v2.0 5 votes vote down vote up
def __enter__(self):
        self._old_au_local_m2m = AbstractUser._meta.local_many_to_many
        self._old_pm_local_m2m = PermissionsMixin._meta.local_many_to_many
        groups = models.ManyToManyField(Group, blank=True)
        groups.contribute_to_class(PermissionsMixin, "groups")
        user_permissions = models.ManyToManyField(Permission, blank=True)
        user_permissions.contribute_to_class(PermissionsMixin, "user_permissions")
        PermissionsMixin._meta.local_many_to_many = [groups, user_permissions]
        AbstractUser._meta.local_many_to_many = [groups, user_permissions] 
Example 50
Project: djexp   Author: Djangolify   File: normalizers.py    GNU General Public License v3.0 5 votes vote down vote up
def normalize_relations(field):
	field_type = type(field)
	if field_type is models.ForeignKey:
		return 'ForeignKey({})'.format(get_rel_model(field).__name__)
	if field_type is models.ManyToManyField:
		return 'ManyToManyField({})'.format(get_rel_model(field).__name__)
	if field_type is models.OneToOneField:
		return 'OneToOneField({})'.format(get_rel_model(field).__name__)
	return None 
Example 51
Project: opadmin   Author: cc0411   File: edit.py    GNU General Public License v3.0 5 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        # If it uses an intermediary model that isn't auto created, don't show
        # a field in admin.
        if isinstance(db_field, models.ManyToManyField) and not db_field.rel.through._meta.auto_created:
            return None

        attrs = self.get_field_attrs(db_field, **kwargs)
        return db_field.formfield(**dict(attrs, **kwargs)) 
Example 52
Project: opadmin   Author: cc0411   File: edit.py    GNU General Public License v3.0 5 votes vote down vote up
def get_field_style(self, db_field, style, **kwargs):
        if style in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
            attrs = {'widget': widgets.AdminRadioSelect(
                attrs={'inline': 'inline' if style == 'radio-inline' else ''})}
            if db_field.choices:
                attrs['choices'] = db_field.get_choices(
                    include_blank=db_field.blank,
                    blank_choice=[('', _('Null'))]
                )
            return attrs

        if style in ('checkbox', 'checkbox-inline') and isinstance(db_field, models.ManyToManyField):
            return {'widget': widgets.AdminCheckboxSelect(attrs={'inline': style == 'checkbox-inline'}),
                    'help_text': None} 
Example 53
Project: opadmin   Author: cc0411   File: edit.py    GNU General Public License v3.0 5 votes vote down vote up
def get_form_datas(self):
        # Prepare the dict of initial data from the request.
        # We have to special-case M2Ms as a list of comma-separated PKs.
        if self.request_method == 'get':
            initial = dict(self.request.GET.items())
            for k in initial:
                try:
                    f = self.opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            return {'initial': initial}
        else:
            return {'data': self.request.POST, 'files': self.request.FILES} 
Example 54
Project: opadmin   Author: cc0411   File: multiselect.py    GNU General Public License v3.0 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        if style == 'm2m_transfer' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleTransfer(db_field.verbose_name, False), 'help_text': ''}
        if style == 'm2m_dropdown' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleDropdown, 'help_text': ''}
        return attrs 
Example 55
Project: opadmin   Author: cc0411   File: quickform.py    GNU General Public License v3.0 5 votes vote down vote up
def formfield_for_dbfield(self, formfield, db_field, **kwargs):
        if formfield and self.model in self.admin_site._registry and isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
            rel_model = get_model_from_relation(db_field)
            if rel_model in self.admin_site._registry and self.has_model_perm(rel_model, 'add'):
                add_url = self.get_model_url(rel_model, 'add')
                formfield.widget = RelatedFieldWidgetWrapper(
                    formfield.widget, db_field.rel, add_url, self.get_model_url(self.model, 'add'))
        return formfield 
Example 56
Project: StormOnline   Author: stormsha   File: edit.py    Apache License 2.0 5 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        # If it uses an intermediary model that isn't auto created, don't show
        # a field in admin.
        if isinstance(db_field, models.ManyToManyField) and not db_field.rel.through._meta.auto_created:
            return None

        attrs = self.get_field_attrs(db_field, **kwargs)
        return db_field.formfield(**dict(attrs, **kwargs)) 
Example 57
Project: StormOnline   Author: stormsha   File: edit.py    Apache License 2.0 5 votes vote down vote up
def get_field_style(self, db_field, style, **kwargs):
        if style in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
            attrs = {'widget': widgets.AdminRadioSelect(
                attrs={'inline': 'inline' if style == 'radio-inline' else ''})}
            if db_field.choices:
                attrs['choices'] = db_field.get_choices(
                    include_blank=db_field.blank,
                    blank_choice=[('', _('Null'))]
                )
            return attrs

        if style in ('checkbox', 'checkbox-inline') and isinstance(db_field, models.ManyToManyField):
            return {'widget': widgets.AdminCheckboxSelect(attrs={'inline': style == 'checkbox-inline'}),
                    'help_text': None} 
Example 58
Project: StormOnline   Author: stormsha   File: edit.py    Apache License 2.0 5 votes vote down vote up
def get_form_datas(self):
        # Prepare the dict of initial data from the request.
        # We have to special-case M2Ms as a list of comma-separated PKs.
        if self.request_method == 'get':
            initial = dict(self.request.GET.items())
            for k in initial:
                try:
                    f = self.opts.get_field(k)
                except models.FieldDoesNotExist:
                    continue
                if isinstance(f, models.ManyToManyField):
                    initial[k] = initial[k].split(",")
            return {'initial': initial}
        else:
            return {'data': self.request.POST, 'files': self.request.FILES} 
Example 59
Project: StormOnline   Author: stormsha   File: multiselect.py    Apache License 2.0 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        if style == 'm2m_transfer' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleTransfer(db_field.verbose_name, False), 'help_text': ''}
        if style == 'm2m_dropdown' and isinstance(db_field, ManyToManyField):
            return {'widget': SelectMultipleDropdown, 'help_text': ''}
        return attrs 
Example 60
Project: StormOnline   Author: stormsha   File: quickform.py    Apache License 2.0 5 votes vote down vote up
def formfield_for_dbfield(self, formfield, db_field, **kwargs):
        if formfield and self.model in self.admin_site._registry and isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
            rel_model = get_model_from_relation(db_field)
            if rel_model in self.admin_site._registry and self.has_model_perm(rel_model, 'add'):
                add_url = self.get_model_url(rel_model, 'add')
                formfield.widget = RelatedFieldWidgetWrapper(
                    formfield.widget, db_field.rel, add_url, self.get_model_url(self.model, 'add'))
        return formfield 
Example 61
Project: django-object-manager   Author: K0Te   File: object_manager.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _is_custom(self, model, **kwargs):
        fields = {field.name: field for field in model._meta.get_fields()}
        for name in kwargs:
            if not isinstance(fields[name], (ManyToManyField, ManyToManyRel)):
                return True
        return False 
Example 62
Project: django-idcops   Author: Wenvki   File: edit.py    Apache License 2.0 5 votes vote down vote up
def get_form_kwargs(self):
        kwargs = super(NewModelView, self).get_form_kwargs()
        params = self.request.GET.dict()
        mfields = [f.attname for f in self.opts.fields]
        for k in params.keys():
            if k in mfields:
                kwargs.update({k: params[k]})
        related_models = []
        for f in self.opts.get_fields():
            if isinstance(f, (models.ForeignKey, models.ManyToManyField)):
                if f.related_model:
                    related_models.append(f.related_model)
        if User in related_models:
            kwargs.update({'user': self.request.user})
        return kwargs 
Example 63
Project: django-idcops   Author: Wenvki   File: edit.py    Apache License 2.0 5 votes vote down vote up
def get_form_kwargs(self):
        kwargs = super(EditModelView, self).get_form_kwargs()
        params = self.request.GET.dict()
        mfields = [f.attname for f in self.opts.fields]
        for k in params.keys():
            if k in mfields:
                kwargs.update({k: params[k]})
        related_models = []
        for f in self.opts.get_fields():
            if isinstance(f, (models.ForeignKey, models.ManyToManyField)):
                if f.related_model:
                    related_models.append(f.related_model)
        if User in related_models:
            kwargs.update({'user': self.request.user})
        return kwargs 
Example 64
Project: TESTGIT   Author: B-ROY   File: validation.py    Apache License 2.0 5 votes vote down vote up
def check_field_spec(self, cls, model, flds, label):
        """
        Validate the fields specification in `flds` from a ModelAdmin subclass
        `cls` for the `model` model. Use `label` for reporting problems to the user.

        The fields specification can be a ``fields`` option or a ``fields``
        sub-option from a ``fieldsets`` option component.
        """
        for fields in flds:
            # The entry in fields might be a tuple. If it is a standalone
            # field, make it into a tuple to make processing easier.
            if type(fields) != tuple:
                fields = (fields,)
            for field in fields:
                if field in cls.readonly_fields:
                    # Stuff can be put in fields that isn't actually a
                    # model field if it's in readonly_fields,
                    # readonly_fields will handle the validation of such
                    # things.
                    continue
                try:
                    f = model._meta.get_field(field)
                except models.FieldDoesNotExist:
                    # If we can't find a field on the model that matches, it could be an
                    # extra field on the form; nothing to check so move on to the next field.
                    continue
                if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created:
                    raise ImproperlyConfigured("'%s.%s' "
                        "can't include the ManyToManyField field '%s' because "
                        "'%s' manually specifies a 'through' model." % (
                            cls.__name__, label, field, field)) 
Example 65
Project: TESTGIT   Author: B-ROY   File: validation.py    Apache License 2.0 5 votes vote down vote up
def validate_raw_id_fields(self, cls, model):
        " Validate that raw_id_fields only contains field names that are listed on the model. "
        if hasattr(cls, 'raw_id_fields'):
            check_isseq(cls, 'raw_id_fields', cls.raw_id_fields)
            for idx, field in enumerate(cls.raw_id_fields):
                f = get_field(cls, model, 'raw_id_fields', field)
                if not isinstance(f, (models.ForeignKey, models.ManyToManyField)):
                    raise ImproperlyConfigured("'%s.raw_id_fields[%d]', '%s' must "
                            "be either a ForeignKey or ManyToManyField."
                            % (cls.__name__, idx, field)) 
Example 66
Project: TESTGIT   Author: B-ROY   File: validation.py    Apache License 2.0 5 votes vote down vote up
def validate_filter_vertical(self, cls, model):
        " Validate that filter_vertical is a sequence of field names. "
        if hasattr(cls, 'filter_vertical'):
            check_isseq(cls, 'filter_vertical', cls.filter_vertical)
            for idx, field in enumerate(cls.filter_vertical):
                f = get_field(cls, model, 'filter_vertical', field)
                if not isinstance(f, models.ManyToManyField):
                    raise ImproperlyConfigured("'%s.filter_vertical[%d]' must be "
                        "a ManyToManyField." % (cls.__name__, idx)) 
Example 67
Project: AneMo   Author: jspargo   File: autodetector.py    GNU General Public License v2.0 5 votes vote down vote up
def generate_altered_fields(self):
        """
        Fields that have been altered.
        """
        for app_label, model_name, field_name in sorted(self.old_field_keys.intersection(self.new_field_keys)):
            # Did the field change?
            old_model_name = self.renamed_models.get((app_label, model_name), model_name)
            old_field_name = self.renamed_fields.get((app_label, model_name, field_name), field_name)
            old_field = self.old_apps.get_model(app_label, old_model_name)._meta.get_field_by_name(old_field_name)[0]
            new_field = self.new_apps.get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0]
            # Implement any model renames on relations; these are handled by RenameModel
            # so we need to exclude them from the comparison
            if hasattr(new_field, "rel") and getattr(new_field.rel, "to", None):
                rename_key = (
                    new_field.rel.to._meta.app_label,
                    new_field.rel.to._meta.object_name.lower(),
                )
                if rename_key in self.renamed_models:
                    new_field.rel.to = old_field.rel.to
            old_field_dec = self.deep_deconstruct(old_field)
            new_field_dec = self.deep_deconstruct(new_field)
            if old_field_dec != new_field_dec:
                preserve_default = True
                if (old_field.null and not new_field.null and not new_field.has_default() and
                        not isinstance(new_field, models.ManyToManyField)):
                    field = new_field.clone()
                    new_default = self.questioner.ask_not_null_alteration(field_name, model_name)
                    if new_default is not models.NOT_PROVIDED:
                        field.default = new_default
                        preserve_default = False
                else:
                    field = new_field
                self.add_operation(
                    app_label,
                    operations.AlterField(
                        model_name=model_name,
                        name=field_name,
                        field=field,
                        preserve_default=preserve_default,
                    )
                ) 
Example 68
Project: AneMo   Author: jspargo   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def __set__(self, instance, value):
        if not self.related.field.rel.through._meta.auto_created:
            opts = self.related.field.rel.through._meta
            raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name))

        manager = self.__get__(instance)
        manager.clear()
        manager.add(*value) 
Example 69
Project: AneMo   Author: jspargo   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def __set__(self, instance, value):
        if not self.field.rel.through._meta.auto_created:
            opts = self.field.rel.through._meta
            raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model.  Use %s.%s's Manager instead." % (opts.app_label, opts.object_name))

        manager = self.__get__(instance)
        # clear() can change expected output of 'value' queryset, we force evaluation
        # of queryset before clear; ticket #19816
        value = tuple(value)
        manager.clear()
        manager.add(*value) 
Example 70
Project: AneMo   Author: jspargo   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(ManyToManyField, self).deconstruct()
        # Handle the simpler arguments
        if self.db_table is not None:
            kwargs['db_table'] = self.db_table
        if self.rel.db_constraint is not True:
            kwargs['db_constraint'] = self.rel.db_constraint
        if self.rel.related_name is not None:
            kwargs['related_name'] = self.rel.related_name
        if self.rel.related_query_name is not None:
            kwargs['related_query_name'] = self.rel.related_query_name
        # Rel needs more work.
        if isinstance(self.rel.to, six.string_types):
            kwargs['to'] = self.rel.to
        else:
            kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name)
        if getattr(self.rel, 'through', None) is not None:
            if isinstance(self.rel.through, six.string_types):
                kwargs['through'] = self.rel.through
            elif not self.rel.through._meta.auto_created:
                kwargs['through'] = "%s.%s" % (self.rel.through._meta.app_label, self.rel.through._meta.object_name)
        # If swappable is True, then see if we're actually pointing to the target
        # of a swap.
        swappable_setting = self.swappable_setting
        if swappable_setting is not None:
            # If it's already a settings reference, error
            if hasattr(kwargs['to'], "setting_name"):
                if kwargs['to'].setting_name != swappable_setting:
                    raise ValueError("Cannot deconstruct a ManyToManyField pointing to a model that is swapped in place of more than one model (%s and %s)" % (kwargs['to'].setting_name, swappable_setting))
            # Set it
            from django.db.migrations.writer import SettingsReference
            kwargs['to'] = SettingsReference(
                kwargs['to'],
                swappable_setting,
            )
        return name, path, args, kwargs 
Example 71
Project: AneMo   Author: jspargo   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def contribute_to_class(self, cls, name):
        # To support multiple relations to self, it's useful to have a non-None
        # related name on symmetrical relations for internal reasons. The
        # concept doesn't make a lot of sense externally ("you want me to
        # specify *what* on my non-reversible relation?!"), so we set it up
        # automatically. The funky name reduces the chance of an accidental
        # clash.
        if self.rel.symmetrical and (self.rel.to == "self" or self.rel.to == cls._meta.object_name):
            self.rel.related_name = "%s_rel_+" % name

        super(ManyToManyField, self).contribute_to_class(cls, name)

        # The intermediate m2m model is not auto created if:
        #  1) There is a manually specified intermediate, or
        #  2) The class owning the m2m field is abstract.
        #  3) The class owning the m2m field has been swapped out.
        if not self.rel.through and not cls._meta.abstract and not cls._meta.swapped:
            self.rel.through = create_many_to_many_intermediary_model(self, cls)

        # Add the descriptor for the m2m relation
        setattr(cls, self.name, ReverseManyRelatedObjectsDescriptor(self))

        # Set up the accessor for the m2m table name for the relation
        self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta)

        # Populate some necessary rel arguments so that cross-app relations
        # work correctly.
        if isinstance(self.rel.through, six.string_types):
            def resolve_through_model(field, model, cls):
                field.rel.through = model
            add_lazy_relation(cls, self, self.rel.through, resolve_through_model) 
Example 72
Project: AneMo   Author: jspargo   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        defaults = {
            'form_class': forms.ModelMultipleChoiceField,
            'queryset': self.rel.to._default_manager.using(db),
        }
        defaults.update(kwargs)
        # If initial is passed in, it's a list of related objects, but the
        # MultipleChoiceField takes a list of IDs.
        if defaults.get('initial') is not None:
            initial = defaults['initial']
            if callable(initial):
                initial = initial()
            defaults['initial'] = [i._get_pk_val() for i in initial]
        return super(ManyToManyField, self).formfield(**defaults) 
Example 73
Project: AneMo   Author: jspargo   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def db_type(self, connection):
        # A ManyToManyField is not represented by a single column,
        # so return None.
        return None 
Example 74
Project: AneMo   Author: jspargo   File: checks.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_filter_item(self, cls, model, field_name, label):
        """ Check one item of `filter_vertical` or `filter_horizontal`, i.e.
        check that given field exists and is a ManyToManyField. """

        try:
            field = model._meta.get_field(field_name)
        except models.FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=cls, id='admin.E019')
        else:
            if not isinstance(field, models.ManyToManyField):
                return must_be('a ManyToManyField', option=label, obj=cls, id='admin.E020')
            else:
                return [] 
Example 75
Project: chattR   Author: patrickstocklin   File: autodetector.py    GNU General Public License v2.0 4 votes vote down vote up
def generate_altered_fields(self):
        """
        Fields that have been altered.
        """
        for app_label, model_name, field_name in sorted(self.old_field_keys.intersection(self.new_field_keys)):
            # Did the field change?
            old_model_name = self.renamed_models.get((app_label, model_name), model_name)
            old_field_name = self.renamed_fields.get((app_label, model_name, field_name), field_name)
            old_field = self.old_apps.get_model(app_label, old_model_name)._meta.get_field(old_field_name)
            new_field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
            # Implement any model renames on relations; these are handled by RenameModel
            # so we need to exclude them from the comparison
            if hasattr(new_field, "rel") and getattr(new_field.rel, "to", None):
                rename_key = (
                    new_field.rel.to._meta.app_label,
                    new_field.rel.to._meta.model_name,
                )
                if rename_key in self.renamed_models:
                    new_field.rel.to = old_field.rel.to
            old_field_dec = self.deep_deconstruct(old_field)
            new_field_dec = self.deep_deconstruct(new_field)
            if old_field_dec != new_field_dec:
                both_m2m = (
                    isinstance(old_field, models.ManyToManyField) and
                    isinstance(new_field, models.ManyToManyField)
                )
                neither_m2m = (
                    not isinstance(old_field, models.ManyToManyField) and
                    not isinstance(new_field, models.ManyToManyField)
                )
                if both_m2m or neither_m2m:
                    # Either both fields are m2m or neither is
                    preserve_default = True
                    if (old_field.null and not new_field.null and not new_field.has_default() and
                            not isinstance(new_field, models.ManyToManyField)):
                        field = new_field.clone()
                        new_default = self.questioner.ask_not_null_alteration(field_name, model_name)
                        if new_default is not models.NOT_PROVIDED:
                            field.default = new_default
                            preserve_default = False
                    else:
                        field = new_field
                    self.add_operation(
                        app_label,
                        operations.AlterField(
                            model_name=model_name,
                            name=field_name,
                            field=field,
                            preserve_default=preserve_default,
                        )
                    )
                else:
                    # We cannot alter between m2m and concrete fields
                    self._generate_removed_field(app_label, model_name, field_name)
                    self._generate_added_field(app_label, model_name, field_name) 
Example 76
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 4 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        defaults = {
            'form_class': forms.ModelMultipleChoiceField,
            'queryset': self.rel.to._default_manager.using(db),
        }
        defaults.update(kwargs)
        # If initial is passed in, it's a list of related objects, but the
        # MultipleChoiceField takes a list of IDs.
        if defaults.get('initial') is not None:
            initial = defaults['initial']
            if callable(initial):
                initial = initial()
            defaults['initial'] = [i._get_pk_val() for i in initial]
        return super(ManyToManyField, self).formfield(**defaults) 
Example 77
Project: chattR   Author: patrickstocklin   File: checks.py    GNU General Public License v2.0 4 votes vote down vote up
def _check_list_display_item(self, cls, model, item, label):
        if callable(item):
            return []
        elif hasattr(cls, item):
            return []
        elif hasattr(model, item):
            # getattr(model, item) could be an X_RelatedObjectsDescriptor
            try:
                field = model._meta.get_field(item)
            except FieldDoesNotExist:
                try:
                    field = getattr(model, item)
                except AttributeError:
                    field = None

            if field is None:
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not a "
                        "callable, an attribute of '%s', or an attribute or method on '%s.%s'." % (
                            label, item, cls.__name__, model._meta.app_label, model._meta.object_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E108',
                    )
                ]
            elif isinstance(field, models.ManyToManyField):
                return [
                    checks.Error(
                        "The value of '%s' must not be a ManyToManyField." % label,
                        hint=None,
                        obj=cls,
                        id='admin.E109',
                    )
                ]
            else:
                return []
        else:
            try:
                model._meta.get_field(item)
            except FieldDoesNotExist:
                return [
                    # This is a deliberate repeat of E108; there's more than one path
                    # required to test this condition.
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not a callable, "
                        "an attribute of '%s', or an attribute or method on '%s.%s'." % (
                            label, item, cls.__name__, model._meta.app_label, model._meta.object_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E108',
                    )
                ]
            else:
                return [] 
Example 78
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 4 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        """
        Hook for specifying the form Field instance for a given database Field
        instance.

        If kwargs are given, they're passed to the form Field's constructor.
        """
        request = kwargs.pop("request", None)

        # If the field specifies choices, we don't need to look for special
        # admin widgets - we just need to use a select widget of some kind.
        if db_field.choices:
            return self.formfield_for_choice_field(db_field, request, **kwargs)

        # ForeignKey or ManyToManyFields
        if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
            # Combine the field kwargs with any options for formfield_overrides.
            # Make sure the passed in **kwargs override anything in
            # formfield_overrides because **kwargs is more specific, and should
            # always win.
            if db_field.__class__ in self.formfield_overrides:
                kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)

            # Get the correct formfield.
            if isinstance(db_field, models.ForeignKey):
                formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
            elif isinstance(db_field, models.ManyToManyField):
                formfield = self.formfield_for_manytomany(db_field, request, **kwargs)

            # For non-raw_id fields, wrap the widget with a wrapper that adds
            # extra HTML -- the "add other" interface -- to the end of the
            # rendered output. formfield can be None if it came from a
            # OneToOneField with parent_link=True or a M2M intermediary.
            if formfield and db_field.name not in self.raw_id_fields:
                related_modeladmin = self.admin_site._registry.get(db_field.rel.to)
                wrapper_kwargs = {}
                if related_modeladmin:
                    wrapper_kwargs.update(
                        can_add_related=related_modeladmin.has_add_permission(request),
                        can_change_related=related_modeladmin.has_change_permission(request),
                        can_delete_related=related_modeladmin.has_delete_permission(request),
                    )
                formfield.widget = widgets.RelatedFieldWidgetWrapper(
                    formfield.widget, db_field.rel, self.admin_site, **wrapper_kwargs
                )

            return formfield

        # If we've got overrides for the formfield defined, use 'em. **kwargs
        # passed to formfield_for_dbfield override the defaults.
        for klass in db_field.__class__.mro():
            if klass in self.formfield_overrides:
                kwargs = dict(copy.deepcopy(self.formfield_overrides[klass]), **kwargs)
                return db_field.formfield(**kwargs)

        # For any other type of field, just call its formfield() method.
        return db_field.formfield(**kwargs) 
Example 79
Project: TESTGIT   Author: B-ROY   File: options.py    Apache License 2.0 4 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        """
        Hook for specifying the form Field instance for a given database Field
        instance.

        If kwargs are given, they're passed to the form Field's constructor.
        """
        request = kwargs.pop("request", None)

        # If the field specifies choices, we don't need to look for special
        # admin widgets - we just need to use a select widget of some kind.
        if db_field.choices:
            return self.formfield_for_choice_field(db_field, request, **kwargs)

        # ForeignKey or ManyToManyFields
        if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
            # Combine the field kwargs with any options for formfield_overrides.
            # Make sure the passed in **kwargs override anything in
            # formfield_overrides because **kwargs is more specific, and should
            # always win.
            if db_field.__class__ in self.formfield_overrides:
                kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)

            # Get the correct formfield.
            if isinstance(db_field, models.ForeignKey):
                formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
            elif isinstance(db_field, models.ManyToManyField):
                formfield = self.formfield_for_manytomany(db_field, request, **kwargs)

            # For non-raw_id fields, wrap the widget with a wrapper that adds
            # extra HTML -- the "add other" interface -- to the end of the
            # rendered output. formfield can be None if it came from a
            # OneToOneField with parent_link=True or a M2M intermediary.
            if formfield and db_field.name not in self.raw_id_fields:
                related_modeladmin = self.admin_site._registry.get(
                                                            db_field.rel.to)
                can_add_related = bool(related_modeladmin and
                            related_modeladmin.has_add_permission(request))
                formfield.widget = widgets.RelatedFieldWidgetWrapper(
                            formfield.widget, db_field.rel, self.admin_site,
                            can_add_related=can_add_related)

            return formfield

        # If we've got overrides for the formfield defined, use 'em. **kwargs
        # passed to formfield_for_dbfield override the defaults.
        for klass in db_field.__class__.mro():
            if klass in self.formfield_overrides:
                kwargs = dict(copy.deepcopy(self.formfield_overrides[klass]), **kwargs)
                return db_field.formfield(**kwargs)

        # For any other type of field, just call its formfield() method.
        return db_field.formfield(**kwargs) 
Example 80
Project: AneMo   Author: jspargo   File: autodetector.py    GNU General Public License v2.0 4 votes vote down vote up
def generate_added_fields(self):
        """
        Fields that have been added
        """
        for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys):
            field = self.new_apps.get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0]
            # Fields that are foreignkeys/m2ms depend on stuff
            dependencies = []
            if field.rel and field.rel.to:
                # Account for FKs to swappable models
                swappable_setting = getattr(field, 'swappable_setting', None)
                if swappable_setting is not None:
                    dep_app_label = "__setting__"
                    dep_object_name = swappable_setting
                else:
                    dep_app_label = field.rel.to._meta.app_label
                    dep_object_name = field.rel.to._meta.object_name
                dependencies = [(dep_app_label, dep_object_name, None, True)]
                if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created:
                    dependencies.append((
                        field.rel.through._meta.app_label,
                        field.rel.through._meta.object_name,
                        None,
                        True
                    ))
            # You can't just add NOT NULL fields with no default or fields
            # which don't allow empty strings as default.
            if (not field.null and not field.has_default() and
                    not isinstance(field, models.ManyToManyField) and
                    not (field.blank and field.empty_strings_allowed)):
                field = field.clone()
                field.default = self.questioner.ask_not_null_addition(field_name, model_name)
                self.add_operation(
                    app_label,
                    operations.AddField(
                        model_name=model_name,
                        name=field_name,
                        field=field,
                        preserve_default=False,
                    ),
                    dependencies=dependencies,
                )
            else:
                self.add_operation(
                    app_label,
                    operations.AddField(
                        model_name=model_name,
                        name=field_name,
                        field=field,
                    ),
                    dependencies=dependencies,
                )