Python django.db.models.AutoField() Examples

The following are code examples for showing how to use django.db.models.AutoField(). 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: xadmin_bugfix   Author: vip68   File: batch.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def change_models(self, queryset, cleaned_data):
        n = queryset.count()

        data = {}
        fields = self.opts.fields + self.opts.many_to_many
        for f in fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            data[f] = cleaned_data[f.name]

        if n:
            for obj in queryset:
                for f, v in data.items():
                    f.save_form_data(obj, v)
                obj.save()
            self.message_user(_("Successfully change %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(self.opts, n)
            }, 'success') 
Example 2
Project: django-xadmin   Author: MarkHoo   File: batch.py    MIT License 6 votes vote down vote up
def change_models(self, queryset, cleaned_data):
        n = queryset.count()

        data = {}
        fields = self.opts.fields + self.opts.many_to_many
        for f in fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            data[f] = cleaned_data[f.name]

        if n:
            for obj in queryset:
                for f, v in data.items():
                    f.save_form_data(obj, v)
                obj.save()
            self.message_user(_("Successfully change %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(self.opts, n)
            }, 'success') 
Example 3
Project: django-xadmin   Author: MarkHoo   File: batch.py    MIT License 6 votes vote down vote up
def change_models(self, queryset, cleaned_data):
        n = queryset.count()

        data = {}
        fields = self.opts.fields + self.opts.many_to_many
        for f in fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            data[f] = cleaned_data[f.name]

        if n:
            for obj in queryset:
                for f, v in data.items():
                    f.save_form_data(obj, v)
                obj.save()
            self.message_user(_("Successfully change %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(self.opts, n)
            }, 'success') 
Example 4
Project: django-xadmin   Author: MarkHoo   File: batch.py    MIT License 6 votes vote down vote up
def change_models(self, queryset, cleaned_data):
        n = queryset.count()

        data = {}
        fields = self.opts.fields + self.opts.many_to_many
        for f in fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            data[f] = cleaned_data[f.name]

        if n:
            for obj in queryset:
                for f, v in data.items():
                    f.save_form_data(obj, v)
                obj.save()
            self.message_user(_("Successfully change %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(self.opts, n)
            }, 'success') 
Example 5
Project: openhatch   Author: campbe13   File: 0007_tag_type_remove_s.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'TagType'
        db.create_table('profile_tagtype', (
            ('id', models.AutoField(primary_key=True)),
            ('prefix', models.CharField(max_length=20)),
        ))
        db.send_create_signal('profile', ['TagType'])
        
        # Deleting model 'tagtypes'
        db.delete_table('profile_tagtypes')
        
        # 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, 12, 52, 616983)))
        
        # 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, 12, 12, 53, 45500))) 
Example 6
Project: openhatch   Author: campbe13   File: 0007_tag_type_remove_s.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def backwards(self, orm):
        
        # Deleting model 'TagType'
        db.delete_table('profile_tagtype')
        
        # Adding model 'tagtypes'
        db.create_table('profile_tagtypes', (
            ('prefix', models.CharField(max_length=20)),
            ('id', models.AutoField(primary_key=True)),
        ))
        db.send_create_signal('profile', ['tagtypes'])
        
        # 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, 5, 403945)))
        
        # 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, 12, 9, 5, 292717))) 
Example 7
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 8
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 9
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 10
Project: chattR   Author: patrickstocklin   File: introspection.py    GNU General Public License v2.0 6 votes vote down vote up
def sequence_list(self):
        "Returns a list of information about all DB sequences for all models in all apps."
        from django.apps import apps
        from django.db import models, router

        sequence_list = []

        for app_config in apps.get_app_configs():
            for model in router.get_migratable_models(app_config, self.connection.alias):
                if not model._meta.managed:
                    continue
                if model._meta.swapped:
                    continue
                for f in model._meta.local_fields:
                    if isinstance(f, models.AutoField):
                        sequence_list.append({'table': model._meta.db_table, 'column': f.column})
                        break  # Only one AutoField is allowed per model, so don't bother continuing.

                for f in model._meta.local_many_to_many:
                    # If this is an m2m using an intermediate table,
                    # we don't need to reset the sequence.
                    if f.rel.through is None:
                        sequence_list.append({'table': f.m2m_db_table(), 'column': None})

        return sequence_list 
Example 11
Project: chattR   Author: patrickstocklin   File: operations.py    GNU General Public License v2.0 6 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        query = self._sequence_reset_sql
        for model in model_list:
            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    table_name = self.quote_name(model._meta.db_table)
                    sequence_name = self._get_sequence_name(model._meta.db_table)
                    column_name = self.quote_name(f.column)
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
                    # Only one AutoField is allowed per model, so don't
                    # continue to loop
                    break
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    table_name = self.quote_name(f.m2m_db_table())
                    sequence_name = self._get_sequence_name(f.m2m_db_table())
                    column_name = self.quote_name('id')
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
        return output 
Example 12
Project: opadmin   Author: cc0411   File: batch.py    GNU General Public License v3.0 6 votes vote down vote up
def change_models(self, queryset, cleaned_data):
        n = queryset.count()

        data = {}
        fields = self.opts.fields + self.opts.many_to_many
        for f in fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            data[f] = cleaned_data[f.name]

        if n:
            for obj in queryset:
                for f, v in data.items():
                    f.save_form_data(obj, v)
                obj.save()
            self.message_user(_("Successfully change %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(self.opts, n)
            }, 'success') 
Example 13
Project: StormOnline   Author: stormsha   File: batch.py    Apache License 2.0 6 votes vote down vote up
def change_models(self, queryset, cleaned_data):
        n = queryset.count()

        data = {}
        fields = self.opts.fields + self.opts.many_to_many
        for f in fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            data[f] = cleaned_data[f.name]

        if n:
            for obj in queryset:
                for f, v in data.items():
                    f.save_form_data(obj, v)
                obj.save()
            self.message_user(_("Successfully change %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(self.opts, n)
            }, 'success') 
Example 14
Project: django-atom   Author: ad-m   File: generate_factory.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_creator_for_field(self, name, field, model):
        if isinstance(field, models.AutoField):
            return False
        if isinstance(field, models.ForeignKey):
            return 'factory.SubFactory("{}")'.format(self.get_subfactory_path(field.related_model))
        if isinstance(field, models.CharField):
            return 'factory.Sequence("{0}-{1}-{{0}}".format)'.format(self.safe_name(model.__name__), self.safe_name(name))
        if isinstance(field, models.TextField):
            return "factory.fuzzy.FuzzyText()"
        if isinstance(field, (models.BooleanField, models.NullBooleanField)):
            return "factory.Sequence(lambda n: n % 2 == 0)"
        if isinstance(field, (models.IntegerField, models.SmallIntegerField)):
            return "factory.Sequence(lambda n: n)"
        if isinstance(field, (models.DateTimeField)):
            if field.__class__.__name__ in ['AutoLastModifiedField', 'AutoCreatedField']:  # django-model-utils fields
                return False
            return "factory.fuzzy.FuzzyNaiveDateTime(datetime.datetime(2008, 1, 1))"
        return "UNKNOWN  # TODO: {}".format(field.__class__.__name__) 
Example 15
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 6 votes vote down vote up
def sequence_list(self):
        "Returns a list of information about all DB sequences for all models in all apps."
        from django.apps import apps
        from django.db import models, router

        sequence_list = []

        for app_config in apps.get_app_configs():
            for model in router.get_migratable_models(app_config, self.connection.alias):
                if not model._meta.managed:
                    continue
                if model._meta.swapped:
                    continue
                for f in model._meta.local_fields:
                    if isinstance(f, models.AutoField):
                        sequence_list.append({'table': model._meta.db_table, 'column': f.column})
                        break  # Only one AutoField is allowed per model, so don't bother continuing.

                for f in model._meta.local_many_to_many:
                    # If this is an m2m using an intermediate table,
                    # we don't need to reset the sequence.
                    if f.rel.through is None:
                        sequence_list.append({'table': f.m2m_db_table(), 'column': None})

        return sequence_list 
Example 16
Project: GTDWeb   Author: lanbing510   File: introspection.py    GNU General Public License v2.0 6 votes vote down vote up
def sequence_list(self):
        "Returns a list of information about all DB sequences for all models in all apps."
        from django.apps import apps
        from django.db import models, router

        sequence_list = []

        for app_config in apps.get_app_configs():
            for model in router.get_migratable_models(app_config, self.connection.alias):
                if not model._meta.managed:
                    continue
                if model._meta.swapped:
                    continue
                for f in model._meta.local_fields:
                    if isinstance(f, models.AutoField):
                        sequence_list.append({'table': model._meta.db_table, 'column': f.column})
                        break  # Only one AutoField is allowed per model, so don't bother continuing.

                for f in model._meta.local_many_to_many:
                    # If this is an m2m using an intermediate table,
                    # we don't need to reset the sequence.
                    if f.rel.through is None:
                        sequence_list.append({'table': f.m2m_db_table(), 'column': None})

        return sequence_list 
Example 17
Project: GTDWeb   Author: lanbing510   File: operations.py    GNU General Public License v2.0 6 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        query = self._sequence_reset_sql
        for model in model_list:
            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    table_name = self.quote_name(model._meta.db_table)
                    sequence_name = self._get_sequence_name(model._meta.db_table)
                    column_name = self.quote_name(f.column)
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
                    # Only one AutoField is allowed per model, so don't
                    # continue to loop
                    break
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    table_name = self.quote_name(f.m2m_db_table())
                    sequence_name = self._get_sequence_name(f.m2m_db_table())
                    column_name = self.quote_name('id')
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
        return output 
Example 18
Project: liberator   Author: libscie   File: introspection.py    Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def sequence_list(self):
        "Returns a list of information about all DB sequences for all models in all apps."
        from django.apps import apps
        from django.db import models, router

        sequence_list = []

        for app_config in apps.get_app_configs():
            for model in router.get_migratable_models(app_config, self.connection.alias):
                if not model._meta.managed:
                    continue
                if model._meta.swapped:
                    continue
                for f in model._meta.local_fields:
                    if isinstance(f, models.AutoField):
                        sequence_list.append({'table': model._meta.db_table, 'column': f.column})
                        break  # Only one AutoField is allowed per model, so don't bother continuing.

                for f in model._meta.local_many_to_many:
                    # If this is an m2m using an intermediate table,
                    # we don't need to reset the sequence.
                    if f.remote_field.through is None:
                        sequence_list.append({'table': f.m2m_db_table(), 'column': None})

        return sequence_list 
Example 19
Project: liberator   Author: libscie   File: operations.py    Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        query = self._sequence_reset_sql
        for model in model_list:
            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    table_name = self.quote_name(model._meta.db_table)
                    sequence_name = self._get_sequence_name(model._meta.db_table)
                    column_name = self.quote_name(f.column)
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
                    # Only one AutoField is allowed per model, so don't
                    # continue to loop
                    break
            for f in model._meta.many_to_many:
                if not f.remote_field.through:
                    table_name = self.quote_name(f.m2m_db_table())
                    sequence_name = self._get_sequence_name(f.m2m_db_table())
                    column_name = self.quote_name('id')
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
        return output 
Example 20
Project: banruo   Author: yingshang   File: introspection.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_field_type(self, data_type, description):
        if data_type == cx_Oracle.NUMBER:
            precision, scale = description[4:6]
            if scale == 0:
                if precision > 11:
                    return 'BigAutoField' if description.is_autofield else 'BigIntegerField'
                elif precision == 1:
                    return 'BooleanField'
                elif description.is_autofield:
                    return 'AutoField'
                else:
                    return 'IntegerField'
            elif scale == -127:
                return 'FloatField'

        return super().get_field_type(data_type, description) 
Example 21
def forwards(self, orm):
        # Adding model 'Project'
        db.create_table('api_project', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('organization', self.gf('django.db.models.fields.related.ForeignKey')(related_name='project_organization', to=orm['auth.User'])),
            ('created_by', self.gf('django.db.models.fields.related.ForeignKey')(related_name='project_creator', to=orm['auth.User'])),
            ('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
        ))
        db.send_create_signal('api', ['Project'])

        # Adding unique constraint on 'Project', fields ['name', 'organization']
        db.create_unique('api_project', ['name', 'organization_id'])

        # Adding M2M table for field projects on 'Team'
        db.create_table('api_team_projects', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('team', models.ForeignKey(orm['api.team'], null=False)),
            ('project', models.ForeignKey(orm['api.project'], null=False))
        ))
        db.create_unique('api_team_projects', ['team_id', 'project_id']) 
Example 22
Project: ops22   Author: spark8103   File: batch.py    MIT License 6 votes vote down vote up
def change_models(self, queryset, cleaned_data):
        n = queryset.count()

        data = {}
        for f in self.opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            data[f] = cleaned_data[f.name]

        if n:
            for obj in queryset:
                for f, v in data.items():
                    f.save_form_data(obj, v)
                obj.save()
            self.message_user(_("Successfully change %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(self.opts, n)
            }, 'success') 
Example 23
Project: Fun5G   Author: OpenWinCon   File: introspection.py    Apache License 2.0 6 votes vote down vote up
def sequence_list(self):
        "Returns a list of information about all DB sequences for all models in all apps."
        from django.apps import apps
        from django.db import models, router

        sequence_list = []

        for app_config in apps.get_app_configs():
            for model in router.get_migratable_models(app_config, self.connection.alias):
                if not model._meta.managed:
                    continue
                if model._meta.swapped:
                    continue
                for f in model._meta.local_fields:
                    if isinstance(f, models.AutoField):
                        sequence_list.append({'table': model._meta.db_table, 'column': f.column})
                        break  # Only one AutoField is allowed per model, so don't bother continuing.

                for f in model._meta.local_many_to_many:
                    # If this is an m2m using an intermediate table,
                    # we don't need to reset the sequence.
                    if f.rel.through is None:
                        sequence_list.append({'table': f.m2m_db_table(), 'column': None})

        return sequence_list 
Example 24
Project: Fun5G   Author: OpenWinCon   File: operations.py    Apache License 2.0 6 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        query = self._sequence_reset_sql
        for model in model_list:
            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    table_name = self.quote_name(model._meta.db_table)
                    sequence_name = self._get_sequence_name(model._meta.db_table)
                    column_name = self.quote_name(f.column)
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
                    # Only one AutoField is allowed per model, so don't
                    # continue to loop
                    break
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    table_name = self.quote_name(f.m2m_db_table())
                    sequence_name = self._get_sequence_name(f.m2m_db_table())
                    column_name = self.quote_name('id')
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
        return output 
Example 25
Project: Vigtech-Services   Author: VigTech   File: introspection.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def sequence_list(self):
        "Returns a list of information about all DB sequences for all models in all apps."
        from django.apps import apps
        from django.db import models, router

        sequence_list = []

        for app_config in apps.get_app_configs():
            for model in router.get_migratable_models(app_config, self.connection.alias):
                if not model._meta.managed:
                    continue
                if model._meta.swapped:
                    continue
                for f in model._meta.local_fields:
                    if isinstance(f, models.AutoField):
                        sequence_list.append({'table': model._meta.db_table, 'column': f.column})
                        break  # Only one AutoField is allowed per model, so don't bother continuing.

                for f in model._meta.local_many_to_many:
                    # If this is an m2m using an intermediate table,
                    # we don't need to reset the sequence.
                    if f.rel.through is None:
                        sequence_list.append({'table': f.m2m_db_table(), 'column': None})

        return sequence_list 
Example 26
Project: Vigtech-Services   Author: VigTech   File: operations.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        query = self._sequence_reset_sql
        for model in model_list:
            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    table_name = self.quote_name(model._meta.db_table)
                    sequence_name = self._get_sequence_name(model._meta.db_table)
                    column_name = self.quote_name(f.column)
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
                    # Only one AutoField is allowed per model, so don't
                    # continue to loop
                    break
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    table_name = self.quote_name(f.m2m_db_table())
                    sequence_name = self._get_sequence_name(f.m2m_db_table())
                    column_name = self.quote_name('id')
                    output.append(query % {'sequence': sequence_name,
                                           'table': table_name,
                                           'column': column_name})
        return output 
Example 27
Project: xadmin_bugfix   Author: vip68   File: wizard.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 28
Project: django-xadmin   Author: MarkHoo   File: wizard.py    MIT License 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 29
Project: django-xadmin   Author: MarkHoo   File: wizard.py    MIT License 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 30
Project: omni-forms   Author: omni-digital   File: models.py    MIT License 5 votes vote down vote up
def get_model_fields(self):
        """
        Method to get all model fields for the content type
        associated with the forms specified content type

        :return: List of model field instances
        """

        def is_valid_field(field):
            if isinstance(field, (models.AutoField, ForeignObjectRel, GenericRelation, GenericForeignKey)):
                return False
            else:
                return True
        return list(filter(is_valid_field, self.content_type.model_class()._meta.get_fields())) 
Example 31
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 32
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 33
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 34
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 35
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 36
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 37
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 38
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 39
Project: chattR   Author: patrickstocklin   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance 
Example 40
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 41
Project: djfirebirdsql   Author: nakagami   File: operations.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        query = """EXECUTE BLOCK AS
            DECLARE S VARCHAR(255);
            DECLARE N INT;
            BEGIN
                SELECT MAX(%s) FROM %s INTO :N;
                EXECUTE STATEMENT 'ALTER TABLE %s ALTER COLUMN %s RESTART WITH ' || N;
            END"""
        for model in model_list:
            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    output.append(query % (
                        self.quote_name(f.column),
                        self.quote_name(model._meta.db_table),
                        self.quote_name(model._meta.db_table),
                        self.quote_name(f.column),
                    ))
                    # Only one AutoField is allowed per model, so don't
                    # continue to loop
                    break
            for f in model._meta.many_to_many:
                if not f.remote_field.through:
                    output.append(query % (
                        self.quote_name('id'),
                        self.quote_name(f.m2m_db_table()),
                        self.quote_name(f.m2m_db_table()),
                        self.quote_name('id'),
                    ))
        return output 
Example 42
Project: opadmin   Author: cc0411   File: wizard.py    GNU General Public License v3.0 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 43
Project: StormOnline   Author: stormsha   File: wizard.py    Apache License 2.0 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 44
Project: TESTGIT   Author: B-ROY   File: models.py    Apache License 2.0 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or not f.name in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance 
Example 45
Project: TESTGIT   Author: B-ROY   File: models.py    Apache License 2.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:
                pk_value = 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 46
Project: TESTGIT   Author: B-ROY   File: operations.py    Apache License 2.0 5 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        qn = self.quote_name
        for model in model_list:
            # Use `coalesce` to set the sequence for each model to the max pk value if there are records,
            # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
            # if there are records (as the max pk value is already in use), otherwise set it to false.
            # Use pg_get_serial_sequence to get the underlying sequence name from the table name
            # and column name (available since PostgreSQL 8)

            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
                        (style.SQL_KEYWORD('SELECT'),
                        style.SQL_TABLE(qn(model._meta.db_table)),
                        style.SQL_FIELD(f.column),
                        style.SQL_FIELD(qn(f.column)),
                        style.SQL_FIELD(qn(f.column)),
                        style.SQL_KEYWORD('IS NOT'),
                        style.SQL_KEYWORD('FROM'),
                        style.SQL_TABLE(qn(model._meta.db_table))))
                    break # Only one AutoField is allowed per model, so don't bother continuing.
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
                        (style.SQL_KEYWORD('SELECT'),
                        style.SQL_TABLE(qn(f.m2m_db_table())),
                        style.SQL_FIELD('id'),
                        style.SQL_FIELD(qn('id')),
                        style.SQL_FIELD(qn('id')),
                        style.SQL_KEYWORD('IS NOT'),
                        style.SQL_KEYWORD('FROM'),
                        style.SQL_TABLE(qn(f.m2m_db_table()))))
        return output 
Example 47
Project: TESTGIT   Author: B-ROY   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def convert_values(self, value, field):
        """
        Coerce the value returned by the database backend into a consistent type
        that is compatible with the field type.
        """
        if value is None or field is None:
            return value
        internal_type = field.get_internal_type()
        if internal_type == 'FloatField':
            return float(value)
        elif (internal_type and (internal_type.endswith('IntegerField')
                                 or internal_type == 'AutoField')):
            return int(value)
        return value 
Example 48
Project: TESTGIT   Author: B-ROY   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def sequence_list(self):
        "Returns a list of information about all DB sequences for all models in all apps."
        from django.db import models, router

        apps = models.get_apps()
        sequence_list = []

        for app in apps:
            for model in models.get_models(app):
                if not model._meta.managed:
                    continue
                if model._meta.swapped:
                    continue
                if not router.allow_syncdb(self.connection.alias, model):
                    continue
                for f in model._meta.local_fields:
                    if isinstance(f, models.AutoField):
                        sequence_list.append({'table': model._meta.db_table, 'column': f.column})
                        break  # Only one AutoField is allowed per model, so don't bother continuing.

                for f in model._meta.local_many_to_many:
                    # If this is an m2m using an intermediate table,
                    # we don't need to reset the sequence.
                    if f.rel.through is None:
                        sequence_list.append({'table': f.m2m_db_table(), 'column': None})

        return sequence_list 
Example 49
Project: AneMo   Author: jspargo   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance 
Example 50
Project: AneMo   Author: jspargo   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:
                pk_value = 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: AneMo   Author: jspargo   File: operations.py    GNU General Public License v2.0 5 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        qn = self.quote_name
        for model in model_list:
            # Use `coalesce` to set the sequence for each model to the max pk value if there are records,
            # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
            # if there are records (as the max pk value is already in use), otherwise set it to false.
            # Use pg_get_serial_sequence to get the underlying sequence name from the table name
            # and column name (available since PostgreSQL 8)

            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" %
                        (style.SQL_KEYWORD('SELECT'),
                        style.SQL_TABLE(qn(model._meta.db_table)),
                        style.SQL_FIELD(f.column),
                        style.SQL_FIELD(qn(f.column)),
                        style.SQL_FIELD(qn(f.column)),
                        style.SQL_KEYWORD('IS NOT'),
                        style.SQL_KEYWORD('FROM'),
                        style.SQL_TABLE(qn(model._meta.db_table))))
                    break  # Only one AutoField is allowed per model, so don't bother continuing.
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" %
                        (style.SQL_KEYWORD('SELECT'),
                        style.SQL_TABLE(qn(f.m2m_db_table())),
                        style.SQL_FIELD('id'),
                        style.SQL_FIELD(qn('id')),
                        style.SQL_FIELD(qn('id')),
                        style.SQL_KEYWORD('IS NOT'),
                        style.SQL_KEYWORD('FROM'),
                        style.SQL_TABLE(qn(f.m2m_db_table()))))
        return output 
Example 52
Project: AneMo   Author: jspargo   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def convert_values(self, value, field):
        """
        Coerce the value returned by the database backend into a consistent type
        that is compatible with the field type.
        """
        if value is None or field is None:
            return value
        internal_type = field.get_internal_type()
        if internal_type == 'FloatField':
            return float(value)
        elif (internal_type and (internal_type.endswith('IntegerField')
                                 or internal_type == 'AutoField')):
            return int(value)
        return value 
Example 53
Project: AneMo   Author: jspargo   File: test_operations.py    GNU General Public License v2.0 5 votes vote down vote up
def set_up_test_model(self):
        operations = [migrations.CreateModel(
            "Neighborhood",
            [
                ("id", models.AutoField(primary_key=True)),
                ('name', models.CharField(max_length=100, unique=True)),
                ('geom', fields.MultiPolygonField(srid=4326)),
            ],
        )]
        return self.apply_operations('gis', ProjectState(), operations) 
Example 54
Project: GTDWeb   Author: lanbing510   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance 
Example 55
Project: GTDWeb   Author: lanbing510   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 56
Project: liberator   Author: libscie   File: models.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Leave defaults for fields that aren't in POST data, except for
        # checkbox inputs because they don't appear in POST data if not checked.
        if (f.has_default() and
                form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))):
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance


# ModelForms ################################################################# 
Example 57
Project: banruo   Author: yingshang   File: models.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Construct and return a model instance from the bound ``form``'s
    ``cleaned_data``, but do not save the returned instance to the database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Leave defaults for fields that aren't in POST data, except for
        # checkbox inputs because they don't appear in POST data if not checked.
        if (f.has_default() and
                form[f.name].field.widget.value_omitted_from_data(form.data, form.files, form.add_prefix(f.name))):
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance


# ModelForms ################################################################# 
Example 58
Project: banruo   Author: yingshang   File: introspection.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_sequences(self, cursor, table_name, table_fields=()):
        cursor.execute("""
            SELECT
                user_tab_identity_cols.sequence_name,
                user_tab_identity_cols.column_name
            FROM
                user_tab_identity_cols,
                user_constraints,
                user_cons_columns cols
            WHERE
                user_constraints.constraint_name = cols.constraint_name
                AND user_constraints.table_name = user_tab_identity_cols.table_name
                AND cols.column_name = user_tab_identity_cols.column_name
                AND user_constraints.constraint_type = 'P'
                AND user_tab_identity_cols.table_name = UPPER(%s)
        """, [table_name])
        # Oracle allows only one identity column per table.
        row = cursor.fetchone()
        if row:
            return [{'name': row[0].lower(), 'table': table_name, 'column': row[1].lower()}]
        # To keep backward compatibility for AutoFields that aren't Oracle
        # identity columns.
        for f in table_fields:
            if isinstance(f, models.AutoField):
                return [{'table': table_name, 'column': f.column}]
        return [] 
Example 59
Project: banruo   Author: yingshang   File: operations.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        query = self._sequence_reset_sql
        for model in model_list:
            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    no_autofield_sequence_name = self._get_no_autofield_sequence_name(model._meta.db_table)
                    table = self.quote_name(model._meta.db_table)
                    column = self.quote_name(f.column)
                    output.append(query % {
                        'no_autofield_sequence_name': no_autofield_sequence_name,
                        'table': table,
                        'column': column,
                        'table_name': strip_quotes(table),
                        'column_name': strip_quotes(column),
                    })
                    # Only one AutoField is allowed per model, so don't
                    # continue to loop
                    break
            for f in model._meta.many_to_many:
                if not f.remote_field.through:
                    no_autofield_sequence_name = self._get_no_autofield_sequence_name(f.m2m_db_table())
                    table = self.quote_name(f.m2m_db_table())
                    column = self.quote_name('id')
                    output.append(query % {
                        'no_autofield_sequence_name': no_autofield_sequence_name,
                        'table': table,
                        'column': column,
                        'table_name': strip_quotes(table),
                        'column_name': 'ID',
                    })
        return output 
Example 60
Project: kobo-predict   Author: awemulya   File: 0008_auto_add_user_star_field_to_project.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def forwards(self, orm):
        # Adding M2M table for field user_stars on 'Project'
        m2m_table_name = db.shorten_name(u'api_project_user_stars')
        db.create_table(m2m_table_name, (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('project', models.ForeignKey(orm['api.project'], null=False)),
            ('user', models.ForeignKey(orm[u'auth.user'], null=False))
        ))
        db.create_unique(m2m_table_name, ['project_id', 'user_id']) 
Example 61
Project: ops22   Author: spark8103   File: wizard.py    MIT License 5 votes vote down vote up
def _done(self):
        cleaned_data = self.get_all_cleaned_data()
        exclude = self.admin_view.exclude

        opts = self.admin_view.opts
        instance = self.admin_view.org_obj or self.admin_view.model()

        file_field_list = []
        for f in opts.fields:
            if not f.editable or isinstance(f, models.AutoField) \
                    or not f.name in cleaned_data:
                continue
            if exclude and f.name in exclude:
                continue
            # Defer saving file-type fields until after the other fields, so a
            # callable upload_to can use the values from other fields.
            if isinstance(f, models.FileField):
                file_field_list.append(f)
            else:
                f.save_form_data(instance, cleaned_data[f.name])

        for f in file_field_list:
            f.save_form_data(instance, cleaned_data[f.name])

        instance.save()

        for f in opts.many_to_many:
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

        self.admin_view.new_obj = instance 
Example 62
Project: Fun5G   Author: OpenWinCon   File: models.py    Apache License 2.0 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance 
Example 63
Project: Fun5G   Author: OpenWinCon   File: models.py    Apache License 2.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 64
Project: Vigtech-Services   Author: VigTech   File: models.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance 
Example 65
Project: Vigtech-Services   Author: VigTech   File: models.py    GNU Lesser General Public License v3.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 66
Project: evm   Author: gdgnewdelhi   File: 0004_add_sites.py    MIT License 5 votes vote down vote up
def forwards(self, orm):
        # Adding M2M table for field sites on 'SocialApp'
        db.create_table('socialaccount_socialapp_sites', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('socialapp', models.ForeignKey(orm['socialaccount.socialapp'], null=False)),
            ('site', models.ForeignKey(orm['sites.site'], null=False))
        ))
        db.create_unique('socialaccount_socialapp_sites', ['socialapp_id', 'site_id']) 
Example 67
Project: DroidPot   Author: WhySoGeeky   File: models.py    MIT License 5 votes vote down vote up
def construct_instance(form, instance, fields=None, exclude=None):
    """
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    from django.db import models
    opts = instance._meta

    cleaned_data = form.cleaned_data
    file_field_list = []
    for f in opts.fields:
        if not f.editable or isinstance(f, models.AutoField) \
                or f.name not in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, models.FileField):
            file_field_list.append(f)
        else:
            f.save_form_data(instance, cleaned_data[f.name])

    for f in file_field_list:
        f.save_form_data(instance, cleaned_data[f.name])

    return instance 
Example 68
Project: DroidPot   Author: WhySoGeeky   File: models.py    MIT License 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 69
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 70
Project: chattR   Author: patrickstocklin   File: operations.py    GNU General Public License v2.0 4 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        qn = self.quote_name
        for model in model_list:
            # Use `coalesce` to set the sequence for each model to the max pk value if there are records,
            # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
            # if there are records (as the max pk value is already in use), otherwise set it to false.
            # Use pg_get_serial_sequence to get the underlying sequence name from the table name
            # and column name (available since PostgreSQL 8)

            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                            style.SQL_FIELD(f.column),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                        )
                    )
                    break  # Only one AutoField is allowed per model, so don't bother continuing.
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(f.m2m_db_table())),
                            style.SQL_FIELD('id'),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(f.m2m_db_table()))
                        )
                    )
        return output 
Example 71
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 72
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 73
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 74
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']) 
Example 75
Project: GTDWeb   Author: lanbing510   File: operations.py    GNU General Public License v2.0 4 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        qn = self.quote_name
        for model in model_list:
            # Use `coalesce` to set the sequence for each model to the max pk value if there are records,
            # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
            # if there are records (as the max pk value is already in use), otherwise set it to false.
            # Use pg_get_serial_sequence to get the underlying sequence name from the table name
            # and column name (available since PostgreSQL 8)

            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                            style.SQL_FIELD(f.column),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                        )
                    )
                    break  # Only one AutoField is allowed per model, so don't bother continuing.
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(f.m2m_db_table())),
                            style.SQL_FIELD('id'),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(f.m2m_db_table()))
                        )
                    )
        return output 
Example 76
Project: liberator   Author: libscie   File: models.py    Creative Commons Zero v1.0 Universal 4 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.remote_field and pk.remote_field.parent_link and
                    pk_is_not_editable(pk.remote_field.model._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.remote_field.model._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 77
Project: liberator   Author: libscie   File: operations.py    Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        qn = self.quote_name
        for model in model_list:
            # Use `coalesce` to set the sequence for each model to the max pk value if there are records,
            # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
            # if there are records (as the max pk value is already in use), otherwise set it to false.
            # Use pg_get_serial_sequence to get the underlying sequence name from the table name
            # and column name (available since PostgreSQL 8)

            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                            style.SQL_FIELD(f.column),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                        )
                    )
                    break  # Only one AutoField is allowed per model, so don't bother continuing.
            for f in model._meta.many_to_many:
                if not f.remote_field.through:
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(f.m2m_db_table())),
                            style.SQL_FIELD('id'),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(f.m2m_db_table()))
                        )
                    )
        return output 
Example 78
Project: banruo   Author: yingshang   File: models.py    GNU Lesser General Public License v3.0 4 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.remote_field and pk.remote_field.parent_link and
                    pk_is_not_editable(pk.remote_field.model._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, (ForeignKey, OneToOneField)):
                qs = pk.remote_field.model._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().add_fields(form, index) 
Example 79
Project: Fun5G   Author: OpenWinCon   File: operations.py    Apache License 2.0 4 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        qn = self.quote_name
        for model in model_list:
            # Use `coalesce` to set the sequence for each model to the max pk value if there are records,
            # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
            # if there are records (as the max pk value is already in use), otherwise set it to false.
            # Use pg_get_serial_sequence to get the underlying sequence name from the table name
            # and column name (available since PostgreSQL 8)

            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                            style.SQL_FIELD(f.column),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                        )
                    )
                    break  # Only one AutoField is allowed per model, so don't bother continuing.
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(f.m2m_db_table())),
                            style.SQL_FIELD('id'),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(f.m2m_db_table()))
                        )
                    )
        return output 
Example 80
Project: Vigtech-Services   Author: VigTech   File: operations.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def sequence_reset_sql(self, style, model_list):
        from django.db import models
        output = []
        qn = self.quote_name
        for model in model_list:
            # Use `coalesce` to set the sequence for each model to the max pk value if there are records,
            # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
            # if there are records (as the max pk value is already in use), otherwise set it to false.
            # Use pg_get_serial_sequence to get the underlying sequence name from the table name
            # and column name (available since PostgreSQL 8)

            for f in model._meta.local_fields:
                if isinstance(f, models.AutoField):
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                            style.SQL_FIELD(f.column),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_FIELD(qn(f.column)),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(model._meta.db_table)),
                        )
                    )
                    break  # Only one AutoField is allowed per model, so don't bother continuing.
            for f in model._meta.many_to_many:
                if not f.rel.through:
                    output.append(
                        "%s setval(pg_get_serial_sequence('%s','%s'), "
                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
                            style.SQL_KEYWORD('SELECT'),
                            style.SQL_TABLE(qn(f.m2m_db_table())),
                            style.SQL_FIELD('id'),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_FIELD(qn('id')),
                            style.SQL_KEYWORD('IS NOT'),
                            style.SQL_KEYWORD('FROM'),
                            style.SQL_TABLE(qn(f.m2m_db_table()))
                        )
                    )
        return output