Python django.db.models.ForeignKey() Examples

The following are code examples for showing how to use django.db.models.ForeignKey(). 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: openhatch   Author: campbe13   File: 0023_asheesh_add_person_tag_link_person_column.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding field 'Link_Person_Tag.person'
        db.add_column('profile_link_person_tag', 'person', models.ForeignKey(orm.Person, null=True))
        
        # Deleting field 'Link_Person_Tag.project'
        db.delete_column('profile_link_person_tag', 'project_id')
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 57, 6, 907059)))
        
        # Changing field 'Link_Person_Tag.time_record_was_created'
        db.alter_column('profile_link_person_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 57, 7, 489492)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 57, 7, 310687)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 57, 7, 405992))) 
Example 2
Project: openhatch   Author: campbe13   File: 0023_asheesh_add_person_tag_link_person_column.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def backwards(self, orm):
        
        # Deleting field 'Link_Person_Tag.person'
        db.delete_column('profile_link_person_tag', 'person_id')
        
        # Adding field 'Link_Person_Tag.project'
        db.add_column('profile_link_person_tag', 'project', models.ForeignKey(orm['profile.Person']))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 25, 501145)))
        
        # Changing field 'Link_Person_Tag.time_record_was_created'
        db.alter_column('profile_link_person_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 25, 346041)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 25, 125823)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 25, 843354))) 
Example 3
def forwards(self, orm):
        
        # Deleting field 'Person.username'
        db.delete_column('profile_person', 'username')
        
        # Deleting field 'Person.name'
        db.delete_column('profile_person', 'name')
        
        # Deleting field 'Person.password_hash_md5'
        db.delete_column('profile_person', 'password_hash_md5')
        
        # Changing field 'Person.user'
        db.alter_column('profile_person', 'user_id', models.ForeignKey(orm['auth.User'], unique=True))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 20, 57, 269681)))
        
        # Changing field 'Link_Person_Tag.time_record_was_created'
        db.alter_column('profile_link_person_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 20, 59, 184814)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 20, 58, 641219)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 20, 58, 936615))) 
Example 4
def backwards(self, orm):
        
        # Adding field 'Person.username'
        db.add_column('profile_person', 'username', models.CharField(max_length=200))
        
        # Adding field 'Person.name'
        db.add_column('profile_person', 'name', models.CharField(max_length=200))
        
        # Adding field 'Person.password_hash_md5'
        db.add_column('profile_person', 'password_hash_md5', models.CharField(max_length=200))
        
        # Changing field 'Person.user'
        db.alter_column('profile_person', 'user_id', models.ForeignKey(orm['auth.User']))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 5, 18, 686204)))
        
        # Changing field 'Link_Person_Tag.time_record_was_created'
        db.alter_column('profile_link_person_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 5, 20, 261274)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 5, 16, 979526)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 5, 18, 164561))) 
Example 5
Project: openhatch   Author: campbe13   File: 0022_asheesh_add_person_tag_link.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Link_Person_Tag'
        db.create_table('profile_link_person_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('tag', models.ForeignKey(orm.Tag)),
            ('project', models.ForeignKey(orm.Person)),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 25, 66622))),
            ('source', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Link_Person_Tag'])
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 24, 174516)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 24, 576063)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 24, 667481))) 
Example 6
Project: openhatch   Author: campbe13   File: 0002_annotated_bugs.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'AnnotatedBug'
        db.create_table('bugsets_annotatedbug', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('url', self.gf('django.db.models.fields.URLField')(max_length=200)),
        ))
        db.send_create_signal('bugsets', ['AnnotatedBug'])

        # Adding M2M table for field bugsets on 'AnnotatedBug'
        db.create_table('bugsets_annotatedbug_bugsets', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('annotatedbug', models.ForeignKey(orm['bugsets.annotatedbug'], null=False)),
            ('bugset', models.ForeignKey(orm['bugsets.bugset'], null=False))
        ))
        db.create_unique('bugsets_annotatedbug_bugsets', ['annotatedbug_id', 'bugset_id']) 
Example 7
Project: openhatch   Author: campbe13   File: 0007_remove_skills.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def backwards(self, orm):
        
        # Adding model 'Skill'
        db.create_table('bugsets_skill', (
            ('text', self.gf('django.db.models.fields.CharField')(max_length=200, unique=True)),
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
        ))
        db.send_create_signal('bugsets', ['Skill'])

        # Adding M2M table for field skills on 'AnnotatedBug'
        db.create_table('bugsets_annotatedbug_skills', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('annotatedbug', models.ForeignKey(orm['bugsets.annotatedbug'], null=False)),
            ('skill', models.ForeignKey(orm['bugsets.skill'], null=False))
        ))
        db.create_unique('bugsets_annotatedbug_skills', ['annotatedbug_id', 'skill_id']) 
Example 8
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 6 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(ForeignKey, self).deconstruct()
        del kwargs['to_fields']
        del kwargs['from_fields']
        # Handle the simpler arguments
        if self.db_index:
            del kwargs['db_index']
        else:
            kwargs['db_index'] = False
        if self.db_constraint is not True:
            kwargs['db_constraint'] = self.db_constraint
        # Rel needs more work.
        to_meta = getattr(self.rel.to, "_meta", None)
        if self.rel.field_name and (not to_meta or (to_meta.pk and self.rel.field_name != to_meta.pk.name)):
            kwargs['to_field'] = self.rel.field_name
        return name, path, args, kwargs 
Example 9
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 6 votes vote down vote up
def validate(self, value, model_instance):
        if self.rel.parent_link:
            return
        super(ForeignKey, self).validate(value, model_instance)
        if value is None:
            return

        using = router.db_for_read(model_instance.__class__, instance=model_instance)
        qs = self.rel.to._default_manager.using(using).filter(
            **{self.rel.field_name: value}
        )
        qs = qs.complex_filter(self.get_limit_choices_to())
        if not qs.exists():
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={
                    'model': self.rel.to._meta.verbose_name, 'pk': value,
                    'field': self.rel.field_name, 'value': value,
                },  # 'pk' is included for backwards compatibility
            ) 
Example 10
Project: chattR   Author: patrickstocklin   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 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 11
Project: chattR   Author: patrickstocklin   File: checks.py    GNU General Public License v2.0 6 votes vote down vote up
def _check_radio_fields_key(self, cls, model, field_name, label):
        """ Check that a key of `radio_fields` dictionary is name of existing
        field and that the field is a ForeignKey or has `choices` defined. """

        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.E022')
        else:
            if not (isinstance(field, models.ForeignKey) or field.choices):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not an "
                        "instance of ForeignKey, and does not have a 'choices' definition." % (
                            label, field_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E023',
                    )
                ]
            else:
                return [] 
Example 12
Project: chattR   Author: patrickstocklin   File: validation.py    GNU General Public License v2.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 13
Project: chattR   Author: patrickstocklin   File: layermapping.py    GNU General Public License v2.0 6 votes vote down vote up
def verify_fk(self, feat, rel_model, rel_mapping):
        """
        Given an OGR Feature, the related model and its dictionary mapping,
        this routine will retrieve the related model for the ForeignKey
        mapping.
        """
        # TODO: It is expensive to retrieve a model for every record --
        #  explore if an efficient mechanism exists for caching related
        #  ForeignKey models.

        # Constructing and verifying the related model keyword arguments.
        fk_kwargs = {}
        for field_name, ogr_name in rel_mapping.items():
            fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))

        # Attempting to retrieve and return the related model.
        try:
            return rel_model.objects.using(self.using).get(**fk_kwargs)
        except ObjectDoesNotExist:
            raise MissingForeignKey(
                'No ForeignKey %s model found with keyword arguments: %s' %
                (rel_model.__name__, fk_kwargs)
            ) 
Example 14
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 15
Project: xadmin_bugfix   Author: vip68   File: xversion.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _register_model(admin, model):
    if not hasattr(admin, 'reversion_format'):
        admin.reversion_format = 'json'

    if not is_registered(model):
        inline_fields = []
        for inline in getattr(admin, 'inlines', []):
            inline_model = inline.model
            if getattr(inline, 'generic_inline', False):
                ct_field = getattr(inline, 'ct_field', 'content_type')
                ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
                for field in model._meta.many_to_many:
                    if isinstance(field, GenericRelation) \
                            and field.rel.to == inline_model \
                            and field.object_id_field_name == ct_fk_field \
                            and field.content_type_field_name == ct_field:
                        inline_fields.append(field.name)
                _autoregister(admin, inline_model)
            else:
                fk_name = getattr(inline, 'fk_name', None)
                if not fk_name:
                    for field in inline_model._meta.fields:
                        if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.remote_field.model):
                            fk_name = field.name
                _autoregister(admin, inline_model, follow=[fk_name])
                if not inline_model._meta.get_field(fk_name).remote_field.is_hidden():
                    accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name()
                    inline_fields.append(accessor)
        _autoregister(admin, model, inline_fields) 
Example 16
Project: xadmin_bugfix   Author: vip68   File: relfield.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        # search able fk field
        if style in ('fk-ajax', 'fk-select') and isinstance(db_field, models.ForeignKey):
            if (db_field.remote_field.to in self.admin_view.admin_site._registry) and \
                    self.has_model_perm(db_field.remote_field.to, 'view'):
                db = kwargs.get('using')
                return dict(attrs or {},
                            widget=(style == 'fk-ajax' and ForeignKeySearchWidget or ForeignKeySelectWidget)(db_field.remote_field, self.admin_view, using=db))
        return attrs 
Example 17
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 18
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 19
Project: django-xadmin   Author: MarkHoo   File: xversion.py    MIT License 5 votes vote down vote up
def _register_model(admin, model):
    if not hasattr(admin, 'reversion_format'):
        admin.reversion_format = 'json'

    if not is_registered(model):
        inline_fields = []
        for inline in getattr(admin, 'inlines', []):
            inline_model = inline.model
            if getattr(inline, 'generic_inline', False):
                ct_field = getattr(inline, 'ct_field', 'content_type')
                ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
                for field in model._meta.many_to_many:
                    if isinstance(field, GenericRelation) \
                            and field.rel.to == inline_model \
                            and field.object_id_field_name == ct_fk_field \
                            and field.content_type_field_name == ct_field:
                        inline_fields.append(field.name)
                _autoregister(admin, inline_model)
            else:
                fk_name = getattr(inline, 'fk_name', None)
                if not fk_name:
                    for field in inline_model._meta.fields:
                        if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.rel.to):
                            fk_name = field.name
                _autoregister(admin, inline_model, follow=[fk_name])
                if not inline_model._meta.get_field(fk_name).rel.is_hidden():
                    accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name()
                    inline_fields.append(accessor)
        _autoregister(admin, model, inline_fields) 
Example 20
Project: django-xadmin   Author: MarkHoo   File: relfield.py    MIT License 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        # search able fk field
        if style in ('fk-ajax', 'fk-select') and isinstance(db_field, models.ForeignKey):
            if (db_field.remote_field.to in self.admin_view.admin_site._registry) and \
                    self.has_model_perm(db_field.remote_field.to, 'view'):
                db = kwargs.get('using')
                return dict(attrs or {},
                            widget=(style == 'fk-ajax' and ForeignKeySearchWidget or ForeignKeySelectWidget)(db_field.remote_field, self.admin_view, using=db))
        return attrs 
Example 21
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 22
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 23
Project: django-xadmin   Author: MarkHoo   File: xversion.py    MIT License 5 votes vote down vote up
def _register_model(admin, model):
    if not hasattr(admin, 'reversion_format'):
        admin.reversion_format = 'json'

    if not is_registered(model):
        inline_fields = []
        for inline in getattr(admin, 'inlines', []):
            inline_model = inline.model
            if getattr(inline, 'generic_inline', False):
                ct_field = getattr(inline, 'ct_field', 'content_type')
                ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
                for field in model._meta.many_to_many:
                    if isinstance(field, GenericRelation) \
                            and field.rel.to == inline_model \
                            and field.object_id_field_name == ct_fk_field \
                            and field.content_type_field_name == ct_field:
                        inline_fields.append(field.name)
                _autoregister(admin, inline_model)
            else:
                fk_name = getattr(inline, 'fk_name', None)
                if not fk_name:
                    for field in inline_model._meta.fields:
                        if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.rel.to):
                            fk_name = field.name
                _autoregister(admin, inline_model, follow=[fk_name])
                if not inline_model._meta.get_field(fk_name).rel.is_hidden():
                    accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name()
                    inline_fields.append(accessor)
        _autoregister(admin, model, inline_fields) 
Example 24
Project: django-xadmin   Author: MarkHoo   File: relfield.py    MIT License 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        # search able fk field
        if style in ('fk-ajax', 'fk-select') and isinstance(db_field, models.ForeignKey):
            if (db_field.remote_field.to in self.admin_view.admin_site._registry) and \
                    self.has_model_perm(db_field.remote_field.to, 'view'):
                db = kwargs.get('using')
                return dict(attrs or {},
                            widget=(style == 'fk-ajax' and ForeignKeySearchWidget or ForeignKeySelectWidget)(db_field.remote_field, self.admin_view, using=db))
        return attrs 
Example 25
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 26
Project: django-xadmin   Author: MarkHoo   File: xversion.py    MIT License 5 votes vote down vote up
def _register_model(admin, model):
    if not hasattr(admin, 'reversion_format'):
        admin.reversion_format = 'json'

    if not is_registered(model):
        inline_fields = []
        for inline in getattr(admin, 'inlines', []):
            inline_model = inline.model
            if getattr(inline, 'generic_inline', False):
                ct_field = getattr(inline, 'ct_field', 'content_type')
                ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
                for field in model._meta.many_to_many:
                    if isinstance(field, GenericRelation) \
                            and field.rel.to == inline_model \
                            and field.object_id_field_name == ct_fk_field \
                            and field.content_type_field_name == ct_field:
                        inline_fields.append(field.name)
                _autoregister(admin, inline_model)
            else:
                fk_name = getattr(inline, 'fk_name', None)
                if not fk_name:
                    for field in inline_model._meta.fields:
                        if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.remote_field.model):
                            fk_name = field.name
                _autoregister(admin, inline_model, follow=[fk_name])
                if not inline_model._meta.get_field(fk_name).remote_field.is_hidden():
                    accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name()
                    inline_fields.append(accessor)
        _autoregister(admin, model, inline_fields) 
Example 27
Project: django-xadmin   Author: MarkHoo   File: relfield.py    MIT License 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        # search able fk field
        if style in ('fk-ajax', 'fk-select') and isinstance(db_field, models.ForeignKey):
            if (db_field.remote_field.to in self.admin_view.admin_site._registry) and \
                    self.has_model_perm(db_field.remote_field.to, 'view'):
                db = kwargs.get('using')
                return dict(attrs or {},
                            widget=(style == 'fk-ajax' and ForeignKeySearchWidget or ForeignKeySelectWidget)(db_field.remote_field, self.admin_view, using=db))
        return attrs 
Example 28
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 29
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 30
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_content_type_field(self):
        """
        The model should have a content_type field
        """
        field = OmniModelFormBase._meta.get_field('content_type')
        self.assertIsInstance(field, models.ForeignKey)
        self.assertEqual(field.rel.to, ContentType)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 31
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_content_type_field(self):
        """
        The model should have a content_type field
        """
        field = OmniField._meta.get_field('content_type')
        self.assertIsInstance(field, models.ForeignKey)
        self.assertEqual(field.rel.to, ContentType)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 32
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_real_type_field(self):
        """
        The model should have a real_type field
        """
        field = OmniField._meta.get_field('real_type')
        self.assertIsInstance(field, models.ForeignKey)
        self.assertEqual(field.rel.to, ContentType)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
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: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_related_type_field(self):
        """
        The model should define a related_type field
        """
        field = OmniForeignKeyField._meta.get_field('related_type')
        self.assertIsInstance(field, models.ForeignKey)
        self.assertEqual(field.rel.to, ContentType)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 35
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_content_type_field(self):
        """
        The model should have a content_type field
        """
        field = OmniFormHandler._meta.get_field('content_type')
        self.assertIsInstance(field, models.ForeignKey)
        self.assertEqual(field.rel.to, ContentType)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 36
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_recipient_field_field(self):
        """
        The model should have a recipient_field field
        """
        field = OmniFormEmailConfirmationHandler._meta.get_field('recipient_field')
        self.assertIsInstance(field, models.ForeignKey)
        self.assertEqual(field.rel.to, OmniEmailField)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 37
Project: mezzanine-smartling   Author: Appdynamics   File: managers.py    Apache License 2.0 5 votes vote down vote up
def get_followed_relations(self, obj):
        """Returns an iterable of related models that should be included in the revision data."""
        for relationship in self.follow:
            # Clear foreign key cache.
            try:
                related_field = obj._meta.get_field(relationship)
            except models.FieldDoesNotExist:
                pass
            else:
                if isinstance(related_field, models.ForeignKey):
                    if hasattr(obj, related_field.get_cache_name()):
                        delattr(obj, related_field.get_cache_name())
            # Get the referenced obj(s).
            try:
                related = getattr(obj, relationship)
            except ObjectDoesNotExist:
                continue
            if isinstance(related, models.Model):
                yield related
            elif isinstance(related, (models.Manager, QuerySet)):
                for related_obj in related.all():
                    yield related_obj
            elif related is not None:
                raise TypeError("Cannot follow the relationship {relationship}. Expected a model or QuerySet, found {related}".format(
                    relationship = relationship,
                    related = related,
                )) 
Example 38
Project: mezzanine-smartling   Author: Appdynamics   File: managers.py    Apache License 2.0 5 votes vote down vote up
def get_followed_relations(self, obj):
        """Returns an iterable of related models that should be included in the revision data."""
        for relationship in self.follow:
            # Clear foreign key cache.
            try:
                related_field = obj._meta.get_field(relationship)
            except models.FieldDoesNotExist:
                pass
            else:
                if isinstance(related_field, models.ForeignKey):
                    if hasattr(obj, related_field.get_cache_name()):
                        delattr(obj, related_field.get_cache_name())
            # Get the referenced obj(s).
            try:
                related = getattr(obj, relationship)
            except ObjectDoesNotExist:
                continue
            if isinstance(related, models.Model):
                yield related
            elif isinstance(related, (models.Manager, QuerySet)):
                for related_obj in related.all():
                    yield related_obj
            elif related is not None:
                raise TypeError("Cannot follow the relationship {relationship}. Expected a model or QuerySet, found {related}".format(
                    relationship = relationship,
                    related = related,
                )) 
Example 39
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_choice_queryset_ajax_attrs_foreign_key(kwargs):
    from django.contrib.auth.models import User
    from django.db import models
    from django.db.models import CASCADE

    class FooModel(models.Model):
        user = models.ForeignKey(User, on_delete=CASCADE)

    User.objects.create(username='foo')
    user2 = User.objects.create(username='bar')

    form = Form.from_model(model=FooModel, data={}, **kwargs)
    form.request = RequestFactory().get('/')
    assert form.endpoint_dispatch(key='field/user', value='ar') == dict(results=[{'id': user2.pk, 'text': smart_str(user2)}], more=False, page=1) 
Example 40
Project: openhatch   Author: campbe13   File: 0006_rename_rel_to_project_exp.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Link_ProjectExp_Tag'
        db.create_table('profile_link_projectexp_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('tag', models.ForeignKey(orm.Tag)),
            ('project_exp', models.ForeignKey(orm.ProjectExp)),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 9, 4, 847921))),
            ('source', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Link_ProjectExp_Tag'])
        
        # Adding model 'ProjectExp'
        db.create_table('profile_projectexp', (
            ('id', models.AutoField(primary_key=True)),
            ('person', models.ForeignKey(orm.Person)),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('person_role', models.CharField(max_length=200)),
            ('tags', models.TextField()),
            ('time_record_was_created', models.DateTimeField()),
            ('url', models.URLField(max_length=200)),
            ('description', models.TextField()),
            ('time_start', models.DateTimeField()),
            ('time_finish', models.DateTimeField()),
            ('man_months', models.PositiveIntegerField()),
            ('primary_language', models.CharField(max_length=200)),
            ('source', models.CharField(max_length=100)),
        ))
        db.send_create_signal('profile', ['ProjectExp'])
        
        # Deleting model 'link_persontoprojectrelationship_tag'
        db.delete_table('profile_link_persontoprojectrelationship_tag')
        
        # Deleting model 'persontoprojectrelationship'
        db.delete_table('profile_persontoprojectrelationship')
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 9, 4, 301717))) 
Example 41
Project: openhatch   Author: campbe13   File: 0006_rename_rel_to_project_exp.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def backwards(self, orm):
        
        # Deleting model 'Link_ProjectExp_Tag'
        db.delete_table('profile_link_projectexp_tag')
        
        # Deleting model 'ProjectExp'
        db.delete_table('profile_projectexp')
        
        # Adding model 'link_persontoprojectrelationship_tag'
        db.create_table('profile_link_persontoprojectrelationship_tag', (
            ('person_to_project_relationship', models.ForeignKey(orm['profile.PersonToProjectRelationship'])),
            ('source', models.CharField(max_length=200)),
            ('tag', models.ForeignKey(orm['profile.Tag'])),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 1, 149232))),
            ('id', models.AutoField(primary_key=True)),
        ))
        db.send_create_signal('profile', ['link_persontoprojectrelationship_tag'])
        
        # Adding model 'persontoprojectrelationship'
        db.create_table('profile_persontoprojectrelationship', (
            ('description', models.TextField()),
            ('tags', models.TextField()),
            ('man_months', models.PositiveIntegerField()),
            ('primary_language', models.CharField(max_length=200)),
            ('id', models.AutoField(primary_key=True)),
            ('time_start', models.DateTimeField()),
            ('source', models.CharField(max_length=100)),
            ('url', models.URLField(max_length=200)),
            ('time_record_was_created', models.DateTimeField()),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('person', models.ForeignKey(orm['profile.Person'])),
            ('time_finish', models.DateTimeField()),
            ('person_role', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['persontoprojectrelationship'])
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 1, 569217))) 
Example 42
Project: openhatch   Author: campbe13   File: 0020_asheesh_add_sourceforge_models.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Link_SF_Proj_Dude_FM'
        db.create_table('profile_link_sf_proj_dude_fm', (
            ('id', models.AutoField(primary_key=True)),
            ('person', models.ForeignKey(orm.SourceForgePerson)),
            ('project', models.ForeignKey(orm.SourceForgeProject)),
            ('is_admin', models.BooleanField(default=False)),
            ('position', models.CharField(max_length=200)),
            ('date_collected', models.DateTimeField()),
        ))
        db.send_create_signal('profile', ['Link_SF_Proj_Dude_FM'])
        
        # Adding model 'SourceForgeProject'
        db.create_table('profile_sourceforgeproject', (
            ('id', models.AutoField(primary_key=True)),
            ('unixname', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['SourceForgeProject'])
        
        # Adding model 'SourceForgePerson'
        db.create_table('profile_sourceforgeperson', (
            ('id', models.AutoField(primary_key=True)),
            ('username', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['SourceForgePerson'])
        
        # Adding field 'ProjectExp.favorite'
        db.add_column('profile_projectexp', 'favorite', models.BooleanField(default=False))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 25, 10, 24, 40, 465787)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 25, 10, 24, 40, 858041)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 25, 10, 24, 40, 948895)))
        
        # Creating unique_together for [person, project] on Link_SF_Proj_Dude_FM.
        db.create_unique('profile_link_sf_proj_dude_fm', ['person_id', 'project_id']) 
Example 43
Project: openhatch   Author: campbe13   File: 0001_initial.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Person'
        db.create_table('profile_person', (
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=200)),
            ('username', models.CharField(max_length=200)),
            ('password_hash_md5', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Person'])
        
        # Adding model 'PersonToProjectRelationship'
        db.create_table('profile_persontoprojectrelationship', (
            ('id', models.AutoField(primary_key=True)),
            ('person', models.ForeignKey(orm.Person)),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('person_role', models.CharField(max_length=200)),
            ('tags', models.TextField()),
            ('time_record_was_created', models.DateTimeField()),
            ('url', models.URLField(max_length=200)),
            ('description', models.TextField()),
            ('time_start', models.DateTimeField()),
            ('time_finish', models.DateTimeField()),
            ('man_months', models.PositiveIntegerField()),
            ('primary_language', models.CharField(max_length=200)),
            ('source', models.CharField(max_length=100)),
        ))
        db.send_create_signal('profile', ['PersonToProjectRelationship']) 
Example 44
Project: openhatch   Author: campbe13   File: 0005_add_tag_tagtypes_linkp2prel_to_tag.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'TagTypes'
        db.create_table('profile_tagtypes', (
            ('id', models.AutoField(primary_key=True)),
            ('prefix', models.CharField(max_length=20)),
        ))
        db.send_create_signal('profile', ['TagTypes'])
        
        # Adding model 'Link_PersonToProjectRelationship_Tag'
        db.create_table('profile_link_persontoprojectrelationship_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('tag', models.ForeignKey(orm.Tag)),
            ('person_to_project_relationship', models.ForeignKey(orm.PersonToProjectRelationship)),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 1, 54833))),
            ('source', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Link_PersonToProjectRelationship_Tag'])
        
        # Adding model 'Tag'
        db.create_table('profile_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('text', models.CharField(max_length=50)),
            ('type', models.CharField(max_length=50)),
        ))
        db.send_create_signal('profile', ['Tag'])
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 0, 489277))) 
Example 45
Project: openhatch   Author: campbe13   File: 0058_web_response_and_citation_ignoring.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'RepositoryCommitter'
        db.create_table('profile_repositorycommitter', (
            ('id', orm['profile.repositorycommitter:id']),
            ('project', orm['profile.repositorycommitter:project']),
            ('data_import_attempt', orm['profile.repositorycommitter:data_import_attempt']),
        ))
        db.send_create_signal('profile', ['RepositoryCommitter'])
        
        # Adding ManyToManyField 'Person.blacklisted_repository_committers'
        db.create_table('profile_person_blacklisted_repository_committers', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('person', models.ForeignKey(orm.Person, null=False)),
            ('repositorycommitter', models.ForeignKey(orm.RepositoryCommitter, null=False))
        ))
        
        # Adding field 'Citation.ignored_due_to_duplicate'
        db.add_column('profile_citation', 'ignored_due_to_duplicate', orm['profile.citation:ignored_due_to_duplicate'])
        
        # Adding field 'DataImportAttempt.web_response'
        db.add_column('profile_dataimportattempt', 'web_response', orm['profile.dataimportattempt:web_response'])
        
        # Changing field 'DataImportAttempt.date_created'
        # (to signature: django.db.models.fields.DateTimeField(default=datetime.datetime(2009, 11, 5, 16, 25, 12, 117760)))
        db.alter_column('profile_dataimportattempt', 'date_created', orm['profile.dataimportattempt:date_created'])
        
        # Changing field 'PortfolioEntry.date_created'
        # (to signature: django.db.models.fields.DateTimeField(default=datetime.datetime(2009, 11, 5, 16, 25, 12, 727518)))
        db.alter_column('profile_portfolioentry', 'date_created', orm['profile.portfolioentry:date_created'])
        
        # Changing field 'Citation.date_created'
        # (to signature: django.db.models.fields.DateTimeField(default=datetime.datetime(2009, 11, 5, 16, 25, 12, 794074)))
        db.alter_column('profile_citation', 'date_created', orm['profile.citation:date_created'])
        
        # Creating unique_together for [project, data_import_attempt] on RepositoryCommitter.
        db.create_unique('profile_repositorycommitter', ['project_id', 'data_import_attempt_id']) 
Example 46
Project: openhatch   Author: campbe13   File: 0051_projects_know_which_people_wanna_help_them.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding ManyToManyField 'Project.people_who_wanna_help'
        db.create_table('search_project_people_who_wanna_help', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('project', models.ForeignKey(orm.Project, null=False)),
            ('person', models.ForeignKey(orm['profile.Person'], null=False))
        )) 
Example 47
Project: openhatch   Author: campbe13   File: 0009_add_icon_imagefield_to_project.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding field 'Project.icon'
        db.add_column('search_project', 'icon', orm['search.project:icon'])
        
        # Adding field 'Project.date_icon_was_fetched_from_ohloh'
        db.add_column('search_project', 'date_icon_was_fetched_from_ohloh', orm['search.project:date_icon_was_fetched_from_ohloh'])
        
        # Changing field 'Bug.project'
        # (to signature: django.db.models.fields.related.ForeignKey(to=orm['search.Project']))
        db.alter_column('search_bug', 'project_id', orm['search.bug:project'])
        
        # Changing field 'Bug.good_for_newcomers'
        # (to signature: django.db.models.fields.BooleanField(default=False, blank=True))
        db.alter_column('search_bug', 'good_for_newcomers', orm['search.bug:good_for_newcomers']) 
Example 48
Project: openhatch   Author: campbe13   File: 0009_add_icon_imagefield_to_project.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def backwards(self, orm):
        
        # Deleting field 'Project.icon'
        db.delete_column('search_project', 'icon')
        
        # Deleting field 'Project.date_icon_was_fetched_from_ohloh'
        db.delete_column('search_project', 'date_icon_was_fetched_from_ohloh')
        
        # Changing field 'Bug.project'
        # (to signature: models.ForeignKey(orm['search.Project']))
        db.alter_column('search_bug', 'project_id', orm['search.bug:project'])
        
        # Changing field 'Bug.good_for_newcomers'
        # (to signature: models.BooleanField(default=False))
        db.alter_column('search_bug', 'good_for_newcomers', orm['search.bug:good_for_newcomers']) 
Example 49
Project: openhatch   Author: campbe13   File: 0003_updated_models.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def backwards(self, orm):
        
        # Removing unique constraint on 'AnnotatedBug', fields ['url']
        db.delete_unique('bugsets_annotatedbug', ['url'])

        # Deleting model 'Skill'
        db.delete_table('bugsets_skill')

        # Removing M2M table for field bugs on 'BugSet'
        db.delete_table('bugsets_bugset_bugs')

        # Deleting field 'AnnotatedBug.title'
        db.delete_column('bugsets_annotatedbug', 'title')

        # Deleting field 'AnnotatedBug.description'
        db.delete_column('bugsets_annotatedbug', 'description')

        # Deleting field 'AnnotatedBug.assigned_to'
        db.delete_column('bugsets_annotatedbug', 'assigned_to')

        # Deleting field 'AnnotatedBug.mentor'
        db.delete_column('bugsets_annotatedbug', 'mentor')

        # Deleting field 'AnnotatedBug.time_estimate'
        db.delete_column('bugsets_annotatedbug', 'time_estimate')

        # Deleting field 'AnnotatedBug.status'
        db.delete_column('bugsets_annotatedbug', 'status')

        # Adding M2M table for field bugsets on 'AnnotatedBug'
        db.create_table('bugsets_annotatedbug_bugsets', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('annotatedbug', models.ForeignKey(orm['bugsets.annotatedbug'], null=False)),
            ('bugset', models.ForeignKey(orm['bugsets.bugset'], null=False))
        ))
        db.create_unique('bugsets_annotatedbug_bugsets', ['annotatedbug_id', 'bugset_id'])

        # Removing M2M table for field skills on 'AnnotatedBug'
        db.delete_table('bugsets_annotatedbug_skills') 
Example 50
Project: chattR   Author: patrickstocklin   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def add_fields(self, form, index):
        """Add a hidden field for the object's primary key."""
        from django.db.models import AutoField, OneToOneField, ForeignKey
        self._pk_field = pk = self.model._meta.pk
        # If a pk isn't editable, then it won't be on the form, so we need to
        # add it here so we can tell which object is which when we get the
        # data back. Generally, pk.editable should be false, but for some
        # reason, auto_created pk fields and AutoField's editable attribute is
        # True, so check for that as well.

        def pk_is_not_editable(pk):
            return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField))
                or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk)))
        if pk_is_not_editable(pk) or pk.name not in form.fields:
            if form.is_bound:
                # If we're adding the related instance, ignore its primary key
                # as it could be an auto-generated default which isn't actually
                # in the database.
                pk_value = None if form.instance._state.adding else form.instance.pk
            else:
                try:
                    if index is not None:
                        pk_value = self.get_queryset()[index].pk
                    else:
                        pk_value = None
                except IndexError:
                    pk_value = None
            if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey):
                qs = pk.rel.to._default_manager.get_queryset()
            else:
                qs = self.model._default_manager.get_queryset()
            qs = qs.using(form.instance._state.db)
            if form._meta.widgets:
                widget = form._meta.widgets.get(self._pk_field.name, HiddenInput)
            else:
                widget = HiddenInput
            form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget)
        super(BaseModelFormSet, self).add_fields(form, index) 
Example 51
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(ForeignObject, self).deconstruct()
        kwargs['from_fields'] = self.from_fields
        kwargs['to_fields'] = self.to_fields
        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
        if self.rel.on_delete != CASCADE:
            kwargs['on_delete'] = self.rel.on_delete
        if self.rel.parent_link:
            kwargs['parent_link'] = self.rel.parent_link
        # Work out string form of "to"
        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 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 ForeignKey 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 52
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def check(self, **kwargs):
        errors = super(ForeignKey, self).check(**kwargs)
        errors.extend(self._check_on_delete())
        errors.extend(self._check_unique())
        return errors 
Example 53
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_unique(self, **kwargs):
        return [
            checks.Warning(
                'Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.',
                hint='ForeignKey(unique=True) is usually better served by a OneToOneField.',
                obj=self,
                id='fields.W342',
            )
        ] if self.unique else [] 
Example 54
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def get_default(self):
        "Here we check if the default value is an object and return the to_field if so."
        field_default = super(ForeignKey, self).get_default()
        if isinstance(field_default, self.rel.to):
            return getattr(field_default, self.related_field.attname)
        return field_default 
Example 55
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def contribute_to_related_class(self, cls, related):
        super(ForeignKey, self).contribute_to_related_class(cls, related)
        if self.rel.field_name is None:
            self.rel.field_name = cls._meta.pk.name 
Example 56
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        if isinstance(self.rel.to, six.string_types):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.rel.to))
        defaults = {
            'form_class': forms.ModelChoiceField,
            'queryset': self.rel.to._default_manager.using(db),
            'to_field_name': self.rel.field_name,
        }
        defaults.update(kwargs)
        return super(ForeignKey, self).formfield(**defaults) 
Example 57
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def db_type(self, connection):
        # The database column type of a ForeignKey is the column type
        # of the field to which it points. An exception is if the ForeignKey
        # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField,
        # in which case the column type is simply that of an IntegerField.
        # If the database needs similar types for key fields however, the only
        # thing we can do is making AutoField an IntegerField.
        rel_field = self.related_field
        if (isinstance(rel_field, AutoField) or
                (not connection.features.related_fields_match_type and
                isinstance(rel_field, (PositiveIntegerField,
                                       PositiveSmallIntegerField)))):
            return IntegerField().db_type(connection=connection)
        return rel_field.db_type(connection=connection) 
Example 58
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def get_db_converters(self, connection):
        converters = super(ForeignKey, self).get_db_converters(connection)
        if connection.features.interprets_empty_strings_as_nulls:
            converters += [self.convert_empty_strings]
        return converters 
Example 59
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 5 votes vote down vote up
def get_col(self, alias, output_field=None):
        return super(ForeignKey, self).get_col(alias, output_field or self.related_field) 
Example 60
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 61
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 62
Project: chattR   Author: patrickstocklin   File: validation.py    GNU General Public License v2.0 5 votes vote down vote up
def validate_radio_fields(self, cls, model):
        " Validate that radio_fields is a dictionary of choice or foreign key fields. "
        from django.contrib.admin.options import HORIZONTAL, VERTICAL
        if hasattr(cls, 'radio_fields'):
            check_isdict(cls, 'radio_fields', cls.radio_fields)
            for field, val in cls.radio_fields.items():
                f = get_field(cls, model, 'radio_fields', field)
                if not (isinstance(f, models.ForeignKey) or f.choices):
                    raise ImproperlyConfigured("'%s.radio_fields['%s']' "
                            "is neither an instance of ForeignKey nor does "
                            "have choices set." % (cls.__name__, field))
                if val not in (HORIZONTAL, VERTICAL):
                    raise ImproperlyConfigured("'%s.radio_fields['%s']' "
                            "is neither admin.HORIZONTAL nor admin.VERTICAL."
                            % (cls.__name__, field)) 
Example 63
Project: chattR   Author: patrickstocklin   File: validation.py    GNU General Public License v2.0 5 votes vote down vote up
def validate_fk_name(self, cls, model):
        " Validate that fk_name refers to a ForeignKey. "
        if cls.fk_name:  # default value is None
            f = get_field(cls, model, 'fk_name', cls.fk_name)
            if not isinstance(f, models.ForeignKey):
                raise ImproperlyConfigured("'%s.fk_name is not an instance of "
                        "models.ForeignKey." % cls.__name__) 
Example 64
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 65
Project: xadmin_bugfix   Author: vip68   File: list.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def result_item(self, obj, field_name, row):
        """
        Generates the actual list of data.
        """
        item = ResultItem(field_name, row)
        try:
            f, attr, value = lookup_field(field_name, obj, self)
        except (AttributeError, ObjectDoesNotExist, NoReverseMatch):
            item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE)
        else:
            if f is None:
                item.allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    item.allow_tags = True
                    item.text = boolean_icon(value)
                else:
                    item.text = smart_text(value)
            else:
                if isinstance(f.remote_field, models.ManyToOneRel):
                    field_val = getattr(obj, f.name)
                    if field_val is None:
                        item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE)
                    else:
                        item.text = field_val
                else:
                    item.text = display_for_field(value, f)
                if isinstance(f, models.DateField)\
                    or isinstance(f, models.TimeField)\
                        or isinstance(f, models.ForeignKey):
                    item.classes.append('nowrap')

            item.field = f
            item.attr = attr
            item.value = value

        # If list_display_links not defined, add the link tag to the first field
        if (item.row['is_display_first'] and not self.list_display_links) \
                or field_name in self.list_display_links:
            item.row['is_display_first'] = False
            item.is_display_link = True
            if self.list_display_links_details:
                item_res_uri = self.model_admin_url("detail", getattr(obj, self.pk_attname))
                if item_res_uri:
                    if self.has_change_permission(obj):
                        edit_url = self.model_admin_url("change", getattr(obj, self.pk_attname))
                    else:
                        edit_url = ""
                    item.wraps.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s">%%s</a>'
                                      % (item_res_uri, edit_url, _(u'Details of %s') % str(obj)))
            else:
                url = self.url_for_result(obj)
                item.wraps.append(u'<a href="%s">%%s</a>' % url)

        return item 
Example 66
Project: django-xadmin   Author: MarkHoo   File: list.py    MIT License 4 votes vote down vote up
def result_item(self, obj, field_name, row):
        """
        Generates the actual list of data.
        """
        item = ResultItem(field_name, row)
        try:
            f, attr, value = lookup_field(field_name, obj, self)
        except (AttributeError, ObjectDoesNotExist, NoReverseMatch):
            item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE)
        else:
            if f is None:
                item.allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    item.allow_tags = True
                    item.text = boolean_icon(value)
                else:
                    item.text = smart_text(value)
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(obj, f.name)
                    if field_val is None:
                        item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE)
                    else:
                        item.text = field_val
                else:
                    item.text = display_for_field(value, f)
                if isinstance(f, models.DateField)\
                    or isinstance(f, models.TimeField)\
                        or isinstance(f, models.ForeignKey):
                    item.classes.append('nowrap')

            item.field = f
            item.attr = attr
            item.value = value

        # If list_display_links not defined, add the link tag to the first field
        if (item.row['is_display_first'] and not self.list_display_links) \
                or field_name in self.list_display_links:
            item.row['is_display_first'] = False
            item.is_display_link = True
            if self.list_display_links_details:
                item_res_uri = self.model_admin_url("detail", getattr(obj, self.pk_attname))
                if item_res_uri:
                    if self.has_change_permission(obj):
                        edit_url = self.model_admin_url("change", getattr(obj, self.pk_attname))
                    else:
                        edit_url = ""
                    item.wraps.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s">%%s</a>'
                                     % (item_res_uri, edit_url, _(u'Details of %s') % str(obj)))
            else:
                url = self.url_for_result(obj)
                item.wraps.append(u'<a href="%s">%%s</a>' % url)

        return item 
Example 67
Project: django-xadmin   Author: MarkHoo   File: list.py    MIT License 4 votes vote down vote up
def result_item(self, obj, field_name, row):
        """
        Generates the actual list of data.
        """
        item = ResultItem(field_name, row)
        try:
            f, attr, value = lookup_field(field_name, obj, self)
        except (AttributeError, ObjectDoesNotExist, NoReverseMatch):
            item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE)
        else:
            if f is None:
                item.allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    item.allow_tags = True
                    item.text = boolean_icon(value)
                else:
                    item.text = smart_text(value)
            else:
                if isinstance(f.remote_field, models.ManyToOneRel):
                    field_val = getattr(obj, f.name)
                    if field_val is None:
                        item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE)
                    else:
                        item.text = field_val
                else:
                    item.text = display_for_field(value, f)
                if isinstance(f, models.DateField)\
                    or isinstance(f, models.TimeField)\
                        or isinstance(f, models.ForeignKey):
                    item.classes.append('nowrap')

            item.field = f
            item.attr = attr
            item.value = value

        # If list_display_links not defined, add the link tag to the first field
        if (item.row['is_display_first'] and not self.list_display_links) \
                or field_name in self.list_display_links:
            item.row['is_display_first'] = False
            item.is_display_link = True
            if self.list_display_links_details:
                item_res_uri = self.model_admin_url("detail", getattr(obj, self.pk_attname))
                if item_res_uri:
                    if self.has_change_permission(obj):
                        edit_url = self.model_admin_url("change", getattr(obj, self.pk_attname))
                    else:
                        edit_url = ""
                    item.wraps.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s">%%s</a>'
                                      % (item_res_uri, edit_url, _(u'Details of %s') % str(obj)))
            else:
                url = self.url_for_result(obj)
                item.wraps.append(u'<a href="%s">%%s</a>' % url)

        return item 
Example 68
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_get_name_field():
    from django.db.models import (
        Model,
        IntegerField,
        CharField,
        ForeignKey,
        CASCADE,
    )

    class Foo1(Model):
        a = IntegerField()
        name = CharField(max_length=255)

    class Bar1(Model):
        foo = ForeignKey(Foo1, on_delete=CASCADE)

    class Foo2(Model):
        a = IntegerField()
        fooname = CharField(max_length=255)
        name = CharField(max_length=255)

    class Bar2(Model):
        foo = ForeignKey(Foo2, on_delete=CASCADE)

    class Foo3(Model):
        name = IntegerField()
        fooname = CharField(max_length=255)

    class Bar3(Model):
        foo = ForeignKey(Foo3, on_delete=CASCADE)

    class Foo4(Model):
        fooname = CharField(max_length=255)
        barname = CharField(max_length=255)

    class Bar4(Model):
        foo = ForeignKey(Foo4, on_delete=CASCADE)

    class Foo5(Model):
        blabla = CharField(max_length=255)

    class Bar5(Model):
        foo = ForeignKey(Foo5, on_delete=CASCADE)

    class Foo6(Model):
        a = IntegerField()

    class Bar6(Model):
        foo = ForeignKey(Foo6, on_delete=CASCADE)

    assert get_name_field(Form.from_model(model=Bar1, data={}).fields_by_name.foo) == 'name'
    assert get_name_field(Form.from_model(model=Bar2, data={}).fields_by_name.foo) == 'name'
    assert get_name_field(Form.from_model(model=Bar3, data={}).fields_by_name.foo) == 'fooname'
    assert get_name_field(Form.from_model(model=Bar4, data={}).fields_by_name.foo) == 'fooname'
    assert get_name_field(Form.from_model(model=Bar5, data={}).fields_by_name.foo) == 'blabla'
    with pytest.raises(AssertionError):
        get_name_field(Form.from_model(model=Bar6, data={}).fields_by_name.foo) 
Example 69
def forwards(self, orm):
        
        # Adding field 'ProjectExp.time_start'
        db.add_column('profile_projectexp', 'time_start', models.DateTimeField(null=True))
        
        # Adding field 'ProjectExp.last_touched'
        db.add_column('profile_projectexp', 'last_touched', models.DateTimeField(null=True))
        
        # Adding field 'Tag.tag_type'
        db.add_column('profile_tag', 'tag_type', models.ForeignKey(orm.TagType, null=True))
        
        # Adding field 'ProjectExp.time_finish'
        db.add_column('profile_projectexp', 'time_finish', models.DateTimeField(null=True))
        
        # Deleting field 'Tag.type'
        db.delete_column('profile_tag', 'type')
        
        # Deleting field 'ProjectExp.tags'
        db.delete_column('profile_projectexp', 'tags')
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 14, 38, 36, 403378)))
        
        # Changing field 'Person.last_touched'
        db.alter_column('profile_person', 'last_touched', models.DateTimeField(null=True))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 14, 38, 35, 670600)))
        
        # Changing field 'ProjectExp.url'
        db.alter_column('profile_projectexp', 'url', models.URLField(max_length=200, null=True))
        
        # Changing field 'ProjectExp.man_months'
        db.alter_column('profile_projectexp', 'man_months', models.PositiveIntegerField(null=True))
        
        # Changing field 'ProjectExp.source'
        db.alter_column('profile_projectexp', 'source', models.CharField(max_length=100, null=True))
        
        # Changing field 'ProjectExp.primary_language'
        db.alter_column('profile_projectexp', 'primary_language', models.CharField(max_length=200, null=True))
        
        # Changing field 'ProjectExp.time_record_was_created'
        db.alter_column('profile_projectexp', 'time_record_was_created', models.DateTimeField(null=True)) 
Example 70
Project: openhatch   Author: campbe13   File: 0003_updated_models.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Skill'
        db.create_table('bugsets_skill', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('text', self.gf('django.db.models.fields.CharField')(unique=True, max_length=200)),
        ))
        db.send_create_signal('bugsets', ['Skill'])

        # Adding M2M table for field bugs on 'BugSet'
        db.create_table('bugsets_bugset_bugs', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('bugset', models.ForeignKey(orm['bugsets.bugset'], null=False)),
            ('annotatedbug', models.ForeignKey(orm['bugsets.annotatedbug'], null=False))
        ))
        db.create_unique('bugsets_bugset_bugs', ['bugset_id', 'annotatedbug_id'])

        # Adding field 'AnnotatedBug.title'
        db.add_column('bugsets_annotatedbug', 'title', self.gf('django.db.models.fields.CharField')(default='', max_length=500, blank=True), keep_default=False)

        # Adding field 'AnnotatedBug.description'
        db.add_column('bugsets_annotatedbug', 'description', self.gf('django.db.models.fields.TextField')(default='', blank=True), keep_default=False)

        # Adding field 'AnnotatedBug.assigned_to'
        db.add_column('bugsets_annotatedbug', 'assigned_to', self.gf('django.db.models.fields.CharField')(default='', max_length=200, blank=True), keep_default=False)

        # Adding field 'AnnotatedBug.mentor'
        db.add_column('bugsets_annotatedbug', 'mentor', self.gf('django.db.models.fields.CharField')(default='', max_length=200, blank=True), keep_default=False)

        # Adding field 'AnnotatedBug.time_estimate'
        db.add_column('bugsets_annotatedbug', 'time_estimate', self.gf('django.db.models.fields.CharField')(default='', max_length=200, blank=True), keep_default=False)

        # Adding field 'AnnotatedBug.status'
        db.add_column('bugsets_annotatedbug', 'status', self.gf('django.db.models.fields.CharField')(default='u', max_length=1), keep_default=False)

        # Removing M2M table for field bugsets on 'AnnotatedBug'
        db.delete_table('bugsets_annotatedbug_bugsets')

        # Adding M2M table for field skills on 'AnnotatedBug'
        db.create_table('bugsets_annotatedbug_skills', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('annotatedbug', models.ForeignKey(orm['bugsets.annotatedbug'], null=False)),
            ('skill', models.ForeignKey(orm['bugsets.skill'], null=False))
        ))
        db.create_unique('bugsets_annotatedbug_skills', ['annotatedbug_id', 'skill_id'])

        # Adding unique constraint on 'AnnotatedBug', fields ['url']
        db.create_unique('bugsets_annotatedbug', ['url']) 
Example 71
Project: openhatch   Author: campbe13   File: revisions.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def follow_relationships(self, object_set):
        """
        Follows all the registered relationships in the given set of models to
        yield a set containing the original models plus all their related
        models.
        """
        result_set = set()
        def _follow_relationships(obj):
            # Prevent recursion.
            if obj in result_set:
                return
            result_set.add(obj)
            # Follow relations.
            registration_info = self.get_registration_info(obj.__class__)
            for relationship in registration_info.follow:
                # Clear foreign key cache.
                try:
                    related_field = obj._meta.get_field(relationship)
                except models.FieldDoesNotExist:
                    pass
                else:
                    if isinstance(related_field, models.ForeignKey):
                        if hasattr(obj, related_field.get_cache_name()):
                            delattr(obj, related_field.get_cache_name())
                # Get the referenced obj(s).
                try:
                    related = getattr(obj, relationship, None)
                except obj._meta.get_field_by_name(relationship)[0].model.DoesNotExist:
                    continue
                if isinstance(related, models.Model):
                    _follow_relationships(related) 
                elif isinstance(related, (models.Manager, QuerySet)):
                    for related_obj in related.all():
                        _follow_relationships(related_obj)
                elif related is not None:
                    raise TypeError, "Cannot follow the relationship %r. Expected a model or QuerySet, found %r." % (relationship, related)
            # If a proxy model's parent is registered, add it.
            if obj._meta.proxy:
                parent_cls = obj._meta.parents.keys()[0]
                if self.is_registered(parent_cls):
                    parent_obj = parent_cls.objects.get(pk=obj.pk)
                    _follow_relationships(parent_obj)
        map(_follow_relationships, object_set)
        return result_set 
Example 72
Project: chattR   Author: patrickstocklin   File: models.py    GNU General Public License v2.0 4 votes vote down vote up
def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
    """
    Finds and returns the ForeignKey from model to parent if there is one
    (returns None if can_fail is True and no such field exists). If fk_name is
    provided, assume it is the name of the ForeignKey field. Unless can_fail is
    True, an exception is raised if there is no ForeignKey from model to
    parent_model.
    """
    # avoid circular import
    from django.db.models import ForeignKey
    opts = model._meta
    if fk_name:
        fks_to_parent = [f for f in opts.fields if f.name == fk_name]
        if len(fks_to_parent) == 1:
            fk = fks_to_parent[0]
            if not isinstance(fk, ForeignKey) or \
                    (fk.rel.to != parent_model and
                     fk.rel.to not in parent_model._meta.get_parent_list()):
                raise ValueError(
                    "fk_name '%s' is not a ForeignKey to '%s.%s'."
                    % (fk_name, parent_model._meta.app_label, parent_model._meta.object_name))
        elif len(fks_to_parent) == 0:
            raise ValueError(
                "'%s.%s' has no field named '%s'."
                % (model._meta.app_label, model._meta.object_name, fk_name))
    else:
        # Try to discover what the ForeignKey from model to parent_model is
        fks_to_parent = [
            f for f in opts.fields
            if isinstance(f, ForeignKey)
            and (f.rel.to == parent_model
                or f.rel.to in parent_model._meta.get_parent_list())
        ]
        if len(fks_to_parent) == 1:
            fk = fks_to_parent[0]
        elif len(fks_to_parent) == 0:
            if can_fail:
                return
            raise ValueError(
                "'%s.%s' has no ForeignKey to '%s.%s'." % (
                    model._meta.app_label,
                    model._meta.object_name,
                    parent_model._meta.app_label,
                    parent_model._meta.object_name,
                )
            )
        else:
            raise ValueError(
                "'%s.%s' has more than one ForeignKey to '%s.%s'." % (
                    model._meta.app_label,
                    model._meta.object_name,
                    parent_model._meta.app_label,
                    parent_model._meta.object_name,
                )
            )
    return fk 
Example 73
Project: chattR   Author: patrickstocklin   File: models.py    GNU General Public License v2.0 4 votes vote down vote up
def inlineformset_factory(parent_model, model, form=ModelForm,
                          formset=BaseInlineFormSet, fk_name=None,
                          fields=None, exclude=None, extra=3, can_order=False,
                          can_delete=True, max_num=None, formfield_callback=None,
                          widgets=None, validate_max=False, localized_fields=None,
                          labels=None, help_texts=None, error_messages=None,
                          min_num=None, validate_min=False):
    """
    Returns an ``InlineFormSet`` for the given kwargs.

    You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
    to ``parent_model``.
    """
    fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
    # enforce a max_num=1 when the foreign key to the parent model is unique.
    if fk.unique:
        max_num = 1
    kwargs = {
        'form': form,
        'formfield_callback': formfield_callback,
        'formset': formset,
        'extra': extra,
        'can_delete': can_delete,
        'can_order': can_order,
        'fields': fields,
        'exclude': exclude,
        'min_num': min_num,
        'max_num': max_num,
        'widgets': widgets,
        'validate_min': validate_min,
        'validate_max': validate_max,
        'localized_fields': localized_fields,
        'labels': labels,
        'help_texts': help_texts,
        'error_messages': error_messages,
    }
    FormSet = modelformset_factory(model, **kwargs)
    FormSet.fk = fk
    return FormSet


# Fields ##################################################################### 
Example 74
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 4 votes vote down vote up
def add_lazy_relation(cls, field, relation, operation):
    """
    Adds a lookup on ``cls`` when a related field is defined using a string,
    i.e.::

        class MyModel(Model):
            fk = ForeignKey("AnotherModel")

    This string can be:

        * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive
          relation.

        * The name of a model (i.e "AnotherModel") to indicate another model in
          the same app.

        * An app-label and model name (i.e. "someapp.AnotherModel") to indicate
          another model in a different app.

    If the other model hasn't yet been loaded -- almost a given if you're using
    lazy relationships -- then the relation won't be set up until the
    class_prepared signal fires at the end of model initialization.

    operation is the work that must be performed once the relation can be resolved.
    """
    # Check for recursive relations
    if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
        app_label = cls._meta.app_label
        model_name = cls.__name__

    else:
        # Look for an "app.Model" relation

        if isinstance(relation, six.string_types):
            try:
                app_label, model_name = relation.split(".")
            except ValueError:
                # If we can't split, assume a model in current app
                app_label = cls._meta.app_label
                model_name = relation
        else:
            # it's actually a model class
            app_label = relation._meta.app_label
            model_name = relation._meta.object_name

    # Try to look up the related model, and if it's already loaded resolve the
    # string right away. If get_registered_model raises a LookupError, it means
    # that the related model isn't loaded yet, so we need to pend the relation
    # until the class is prepared.
    try:
        model = cls._meta.apps.get_registered_model(app_label, model_name)
    except LookupError:
        key = (app_label, model_name)
        value = (cls, field, operation)
        cls._meta.apps._pending_lookups.setdefault(key, []).append(value)
    else:
        operation(field, model, cls) 
Example 75
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 4 votes vote down vote up
def create_many_to_many_intermediary_model(field, klass):
    from django.db import models
    managed = True
    if isinstance(field.rel.to, six.string_types) and field.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT:
        to_model = field.rel.to
        to = to_model.split('.')[-1]

        def set_managed(field, model, cls):
            field.rel.through._meta.managed = model._meta.managed or cls._meta.managed
        add_lazy_relation(klass, field, to_model, set_managed)
    elif isinstance(field.rel.to, six.string_types):
        to = klass._meta.object_name
        to_model = klass
        managed = klass._meta.managed
    else:
        to = field.rel.to._meta.object_name
        to_model = field.rel.to
        managed = klass._meta.managed or to_model._meta.managed
    name = '%s_%s' % (klass._meta.object_name, field.name)
    if field.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to == klass._meta.object_name:
        from_ = 'from_%s' % to.lower()
        to = 'to_%s' % to.lower()
    else:
        from_ = klass._meta.model_name
        to = to.lower()
    meta = type(str('Meta'), (object,), {
        'db_table': field._get_m2m_db_table(klass._meta),
        'managed': managed,
        'auto_created': klass,
        'app_label': klass._meta.app_label,
        'db_tablespace': klass._meta.db_tablespace,
        'unique_together': (from_, to),
        'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to},
        'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to},
        'apps': field.model._meta.apps,
    })
    # Construct and return the new class.
    return type(str(name), (models.Model,), {
        'Meta': meta,
        '__module__': klass.__module__,
        from_: models.ForeignKey(
            klass,
            related_name='%s+' % name,
            db_tablespace=field.db_tablespace,
            db_constraint=field.rel.db_constraint,
        ),
        to: models.ForeignKey(
            to_model,
            related_name='%s+' % name,
            db_tablespace=field.db_tablespace,
            db_constraint=field.rel.db_constraint,
        )
    }) 
Example 76
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 77
Project: vaivem   Author: willemarcel   File: 0004_initial.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Usuario'
        db.create_table('emprestimo_usuario', (
            ('nome', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('matricula', self.gf('django.db.models.fields.IntegerField')(max_length=9, primary_key=True)),
            ('categoria', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('email', self.gf('django.db.models.fields.EmailField')(max_length=75)),
            ('telefone', self.gf('django.db.models.fields.CharField')(max_length=15)),
            ('endereco', self.gf('django.db.models.fields.TextField')(max_length=200)),
            ('suspensao', self.gf('django.db.models.fields.DateField')(default=datetime.date(2010, 9, 7), null=True)),
            ('disponivel', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('observacoes', self.gf('django.db.models.fields.TextField')(max_length=300, blank=True)),
        ))
        db.send_create_signal('emprestimo', ['Usuario'])

        # Adding model 'Equipamento'
        db.create_table('emprestimo_equipamento', (
            ('tombo', self.gf('django.db.models.fields.IntegerField')(max_length=10, primary_key=True)),
            ('nome', self.gf('django.db.models.fields.CharField')(max_length=200)),
            ('numeroserie', self.gf('django.db.models.fields.CharField')(max_length=30, null=True)),
            ('categoria', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('disponivel', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('observacoes', self.gf('django.db.models.fields.TextField')(max_length=300, blank=True)),
        ))
        db.send_create_signal('emprestimo', ['Equipamento'])

        # Adding model 'Emprestimo'
        db.create_table('emprestimo_emprestimo', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('usuario', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['emprestimo.Usuario'])),
            ('data_emprestimo', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('prazo_devolucao', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('data_devolucao', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('devolvido', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('funcionario_emprestimo', self.gf('django.db.models.fields.related.ForeignKey')(related_name='emprestimo_emprestimo', null=True, to=orm['auth.User'])),
            ('funcionario_devolucao', self.gf('django.db.models.fields.related.ForeignKey')(related_name='emprestimo_devolucao', null=True, to=orm['auth.User'])),
        ))
        db.send_create_signal('emprestimo', ['Emprestimo'])

        # Adding M2M table for field item on 'Emprestimo'
        db.create_table('emprestimo_emprestimo_item', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('emprestimo', models.ForeignKey(orm['emprestimo.emprestimo'], null=False)),
            ('equipamento', models.ForeignKey(orm['emprestimo.equipamento'], null=False))
        ))
        db.create_unique('emprestimo_emprestimo_item', ['emprestimo_id', 'equipamento_id']) 
Example 78
Project: vaivem   Author: willemarcel   File: 0002_initial.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Usuario'
        db.create_table('emprestimo_usuario', (
            ('nome', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('matricula', self.gf('django.db.models.fields.IntegerField')(max_length=9, primary_key=True)),
            ('categoria', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('email', self.gf('django.db.models.fields.EmailField')(max_length=75)),
            ('telefone', self.gf('django.db.models.fields.CharField')(max_length=15)),
            ('endereco', self.gf('django.db.models.fields.TextField')(max_length=200)),
            ('suspensao', self.gf('django.db.models.fields.DateField')(default=datetime.date(2010, 9, 7), null=True)),
            ('disponivel', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('observacoes', self.gf('django.db.models.fields.TextField')(max_length=300, blank=True)),
        ))
        db.send_create_signal('emprestimo', ['Usuario'])

        # Adding model 'Equipamento'
        db.create_table('emprestimo_equipamento', (
            ('tombo', self.gf('django.db.models.fields.IntegerField')(max_length=10, primary_key=True)),
            ('nome', self.gf('django.db.models.fields.CharField')(max_length=200)),
            ('numeroserie', self.gf('django.db.models.fields.CharField')(max_length=30, null=True)),
            ('categoria', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('disponivel', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('observacoes', self.gf('django.db.models.fields.TextField')(max_length=300, blank=True)),
        ))
        db.send_create_signal('emprestimo', ['Equipamento'])

        # Adding model 'Emprestimo'
        db.create_table('emprestimo_emprestimo', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('usuario', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['emprestimo.Usuario'])),
            ('data_emprestimo', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('prazo_devolucao', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('data_devolucao', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('devolvido', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('funcionario_emprestimo', self.gf('django.db.models.fields.related.ForeignKey')(related_name='emprestimo_emprestimo', null=True, to=orm['auth.User'])),
            ('funcionario_devolucao', self.gf('django.db.models.fields.related.ForeignKey')(related_name='emprestimo_devolucao', null=True, to=orm['auth.User'])),
        ))
        db.send_create_signal('emprestimo', ['Emprestimo'])

        # Adding M2M table for field item on 'Emprestimo'
        db.create_table('emprestimo_emprestimo_item', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('emprestimo', models.ForeignKey(orm['emprestimo.emprestimo'], null=False)),
            ('equipamento', models.ForeignKey(orm['emprestimo.equipamento'], null=False))
        ))
        db.create_unique('emprestimo_emprestimo_item', ['emprestimo_id', 'equipamento_id']) 
Example 79
Project: vaivem   Author: willemarcel   File: 0001_initial.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Usuario'
        db.create_table('emprestimo_usuario', (
            ('nome', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('matricula', self.gf('django.db.models.fields.IntegerField')(max_length=9, primary_key=True)),
            ('categoria', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('email', self.gf('django.db.models.fields.EmailField')(max_length=75)),
            ('telefone', self.gf('django.db.models.fields.CharField')(max_length=15)),
            ('endereco', self.gf('django.db.models.fields.TextField')(max_length=200)),
            ('suspensao', self.gf('django.db.models.fields.DateField')(default=datetime.date(2010, 9, 7), null=True)),
            ('disponivel', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('observacoes', self.gf('django.db.models.fields.TextField')(max_length=300, blank=True)),
        ))
        db.send_create_signal('emprestimo', ['Usuario'])

        # Adding model 'Equipamento'
        db.create_table('emprestimo_equipamento', (
            ('tombo', self.gf('django.db.models.fields.IntegerField')(max_length=10, primary_key=True)),
            ('nome', self.gf('django.db.models.fields.CharField')(max_length=200)),
            ('numeroserie', self.gf('django.db.models.fields.CharField')(max_length=30, null=True)),
            ('categoria', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('disponivel', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('observacoes', self.gf('django.db.models.fields.TextField')(max_length=300, blank=True)),
        ))
        db.send_create_signal('emprestimo', ['Equipamento'])

        # Adding model 'Emprestimo'
        db.create_table('emprestimo_emprestimo', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('usuario', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['emprestimo.Usuario'])),
            ('data_emprestimo', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('prazo_devolucao', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('data_devolucao', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('devolvido', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('funcionario_emprestimo', self.gf('django.db.models.fields.related.ForeignKey')(related_name='emprestimo_emprestimo', null=True, to=orm['auth.User'])),
            ('funcionario_devolucao', self.gf('django.db.models.fields.related.ForeignKey')(related_name='emprestimo_devolucao', null=True, to=orm['auth.User'])),
        ))
        db.send_create_signal('emprestimo', ['Emprestimo'])

        # Adding M2M table for field item on 'Emprestimo'
        db.create_table('emprestimo_emprestimo_item', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('emprestimo', models.ForeignKey(orm['emprestimo.emprestimo'], null=False)),
            ('equipamento', models.ForeignKey(orm['emprestimo.equipamento'], null=False))
        ))
        db.create_unique('emprestimo_emprestimo_item', ['emprestimo_id', 'equipamento_id']) 
Example 80
Project: vaivem   Author: willemarcel   File: 0003_initial.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Usuario'
        db.create_table('emprestimo_usuario', (
            ('nome', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('matricula', self.gf('django.db.models.fields.IntegerField')(max_length=9, primary_key=True)),
            ('categoria', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('email', self.gf('django.db.models.fields.EmailField')(max_length=75)),
            ('telefone', self.gf('django.db.models.fields.CharField')(max_length=15)),
            ('endereco', self.gf('django.db.models.fields.TextField')(max_length=200)),
            ('suspensao', self.gf('django.db.models.fields.DateField')(default=datetime.date(2010, 9, 7), null=True)),
            ('disponivel', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('observacoes', self.gf('django.db.models.fields.TextField')(max_length=300, blank=True)),
        ))
        db.send_create_signal('emprestimo', ['Usuario'])

        # Adding model 'Equipamento'
        db.create_table('emprestimo_equipamento', (
            ('tombo', self.gf('django.db.models.fields.IntegerField')(max_length=10, primary_key=True)),
            ('nome', self.gf('django.db.models.fields.CharField')(max_length=200)),
            ('numeroserie', self.gf('django.db.models.fields.CharField')(max_length=30, null=True)),
            ('categoria', self.gf('django.db.models.fields.CharField')(max_length=50)),
            ('disponivel', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('observacoes', self.gf('django.db.models.fields.TextField')(max_length=300, blank=True)),
        ))
        db.send_create_signal('emprestimo', ['Equipamento'])

        # Adding model 'Emprestimo'
        db.create_table('emprestimo_emprestimo', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('usuario', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['emprestimo.Usuario'])),
            ('data_emprestimo', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('prazo_devolucao', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('data_devolucao', self.gf('django.db.models.fields.DateTimeField')(null=True)),
            ('devolvido', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('funcionario_emprestimo', self.gf('django.db.models.fields.related.ForeignKey')(related_name='emprestimo_emprestimo', null=True, to=orm['auth.User'])),
            ('funcionario_devolucao', self.gf('django.db.models.fields.related.ForeignKey')(related_name='emprestimo_devolucao', null=True, to=orm['auth.User'])),
        ))
        db.send_create_signal('emprestimo', ['Emprestimo'])

        # Adding M2M table for field item on 'Emprestimo'
        db.create_table('emprestimo_emprestimo_item', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('emprestimo', models.ForeignKey(orm['emprestimo.emprestimo'], null=False)),
            ('equipamento', models.ForeignKey(orm['emprestimo.equipamento'], null=False))
        ))
        db.create_unique('emprestimo_emprestimo_item', ['emprestimo_id', 'equipamento_id'])