django.db

Here are the examples of the python api django.db taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

35 Examples 7

Example 1

Project: talk.org Source File: base.py
    def handle(self, *app_labels, **options):
        from django.db import models
        if not app_labels:
            raise CommandError('Enter at least one appname.')
        try:
            app_list = [models.get_app(app_label) for app_label in app_labels]
        except (ImproperlyConfigured, ImportError), e:
            raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
        output = []
        for app in app_list:
            app_output = self.handle_app(app, **options)
            if app_output:
                output.append(app_output)
        return '\n'.join(output)

Example 2

Project: GAE-Bulk-Mailer Source File: base.py
    def handle(self, *app_labels, **options):
        from django.db import models
        if not app_labels:
            raise CommandError('Enter at least one appname.')
        try:
            app_list = [models.get_app(app_label) for app_label in app_labels]
        except (ImproperlyConfigured, ImportError) as e:
            raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
        output = []
        for app in app_list:
            app_output = self.handle_app(app, **options)
            if app_output:
                output.append(app_output)
        return '\n'.join(output)

Example 3

Project: django-cassandra-engine Source File: utils.py
def get_cassandra_connections():
    """
    :return: List of tuples (db_alias, connection) for all cassandra
    connections in DATABASES dict.
    """

    from django.db import connections
    for alias in connections:
        engine = connections[alias].settings_dict.get('ENGINE', '')
        if engine == 'django_cassandra_engine':
            yield alias, connections[alias]

Example 4

Project: django-cassandra-engine Source File: utils.py
def get_cassandra_db_alias():
    from django.db import connections
    for alias in connections:
        engine = connections[alias].settings_dict.get('ENGINE', '')
        if engine == 'django_cassandra_engine':
            return alias

Example 5

Project: wger Source File: tasks.py
def database_exists():
    """Detect if the database exists"""

    # can't be imported in global scope as they already require
    # the settings module during import
    from django.db import DatabaseError
    from django.core.exceptions import ImproperlyConfigured
    from wger.manager.models import User

    try:
        # TODO: Use another model, the User could be deactivated
        User.objects.count()
    except DatabaseError:
        return False
    except ImproperlyConfigured:
        print("Your settings file seems broken")
        sys.exit(0)
    else:
        return True

Example 6

Project: decode-Django Source File: base.py
    def handle(self, *app_labels, **options):
        from django.db import models

        if not app_labels:
            raise CommandError('Enter at least one appname.')

        try:
            app_list = [models.get_app(app_label) for app_label in app_labels]
        except (ImproperlyConfigured, ImportError) as e:
            raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)

        output = []
        for app in app_list:
            app_output = self.handle_app(app, **options)

            if app_output:
                output.append(app_output)

        return '\n'.join(output)

Example 7

Project: django-extensions Source File: test_management_command.py
    def test_works(self):
        from django.db import models

        class PermModel(models.Model):
            class Meta:
                app_label = 'django_extensions'
                permissions = (('test_permission', 'test_permission'),)

        original_stdout = sys.stdout
        out = sys.stdout = StringIO()
        call_command('update_permissions', stdout=out, verbosity=3)
        sys.stdout = original_stdout
        self.assertIn("Can change perm model", out.getvalue())

Example 8

Project: django-push-notifications Source File: runtests.py
Function: tear_down
def tear_down():
	# destroy test database
	from django.db import connection
	connection.creation.destroy_test_db("not_needed")

	# teardown environment
	from django.test.utils import teardown_test_environment
	teardown_test_environment()

Example 9

Project: johnny-cache Source File: cache.py
    def flush_query_cache(self):
        from django.db import connection
        tables = connection.introspection.table_names()
        #seen_models = connection.introspection.installed_models(tables)
        for table in tables:
            # we want this to just work, so invalidate even things in blacklist
            self.keyhandler.invalidate_table(table)

Example 10

Project: django-hvad Source File: basic.py
    def test_translated_attribute_get(self):
        # 'MyDescriptorTestModel' should return the default field value,
        # in case there is no translation
        from hvad.models import TranslatedFields
        from django.db import models

        DEFAULT = 'world'
        class MyDescriptorTestModel(TranslatableModel):
            translations = TranslatedFields(
                hello = models.CharField(default=DEFAULT, max_length=128)
            )
        self.assertEqual(MyDescriptorTestModel.hello, DEFAULT)

Example 11

Project: django-hvad Source File: basic.py
    def test_table_name_separator(self):
        from hvad.models import TranslatedFields
        from django.db import models
        from django.conf import settings
        sep = getattr(settings, 'HVAD_TABLE_NAME_SEPARATOR', '_')
        class MyTableNameTestModel(TranslatableModel):
            translations = TranslatedFields(
                hello = models.CharField(max_length=128)
            )
        self.assertTrue(MyTableNameTestModel._meta.translations_model._meta.db_table.endswith('_mytablenametestmodel%stranslation' % sep))

Example 12

Project: django-hvad Source File: basic.py
    def test_table_name_override(self):
        from hvad.models import TranslatedFields
        from django.db import models
        with self.settings(HVAD_TABLE_NAME_SEPARATOR='O_O'):
            class MyOtherTableNameTestModel(TranslatableModel):
                translations = TranslatedFields(
                    hello = models.CharField(max_length=128)
                )
            self.assertTrue(MyOtherTableNameTestModel._meta.translations_model._meta.db_table.endswith('_myothertablenametestmodelO_Otranslation'))

Example 13

Project: django-hvad Source File: basic.py
    def test_table_name_from_meta(self):
        from hvad.models import TranslatedFields
        from django.db import models
        class MyTableNameTestNamedModel(TranslatableModel):
            translations = TranslatedFields(
                hello = models.CharField(max_length=128),
                meta = {'db_table': 'tests_mymodel_i18n'},
            )
        self.assertEqual(MyTableNameTestNamedModel._meta.translations_model._meta.db_table, 'tests_mymodel_i18n')

Example 14

Project: django-exclusivebooleanfield Source File: test_fields.py
Function: test_atomic
def test_atomic():
    import django
    from django.db import transaction
    from exclusivebooleanfield.fields import transaction_context
    # eg django.VERSION == (1, 4, 9, 'final', 0)
    if django.VERSION[1] >= 6:
        assert transaction_context == transaction.atomic
    else:
        assert transaction_context == transaction.commit_on_success

Example 15

Project: nosedjango Source File: nosedjango.py
Function: transaction
    @property
    def transaction(self):
        from django.db import transaction
        if self.django_version < self.DJANGO_1_7:
            transaction.set_autocommit = _dummy
            transaction.get_autocommit = _dummy
        elif self.django_version > self.DJANGO_1_7:
            transaction.enter_transaction_management = _dummy
            transaction.leave_transaction_management = _dummy
            transaction.managed = _dummy
        return transaction

Example 16

Project: sumatra Source File: __init__.py
Function: clear
    def clear(self):
        """
        Drop all Sumatra-related tables from the database.

        WARNING: this will delete all data. Make sure you have a backup first.
        """
        if not db_config.configured:
            db_config.configure()
        #management.call_command('sqlclear', 'django_store', database=self._db_label)  # this produces coloured output, need no_color option from Django 1.7
        cmds = ["BEGIN;"] + ['DROP TABLE "django_store_{0}";'.format(x)
                             for x in ("record", "record_input_data", "record_dependencies",
                                       "record_platforms", "platforminformation", "datakey", "datastore", "launchmode",
                                       "parameterset", "repository", "dependency", "executable", "project")] + ["COMMIT;"]
        from django.db import connection
        cur = connection.cursor()
        for cmd in cmds:
            cur.execute(cmd)
        db_config._create_databases()

Example 17

Project: pytest-django Source File: live_server_helper.py
    def __init__(self, addr):
        import django
        from django.db import connections
        from django.test.testcases import LiveServerThread
        from django.test.utils import modify_settings

        connections_override = {}
        for conn in connections.all():
            # If using in-memory sqlite databases, pass the connections to
            # the server thread.
            if (conn.settings_dict['ENGINE'] == 'django.db.backends.sqlite3' and
                    conn.settings_dict['NAME'] == ':memory:'):
                # Explicitly enable thread-shareability for this connection
                conn.allow_thread_sharing = True
                connections_override[conn.alias] = conn

        liveserver_kwargs = {'connections_override': connections_override}
        from django.conf import settings
        if 'django.contrib.staticfiles' in settings.INSTALLED_APPS:
            from django.contrib.staticfiles.handlers import StaticFilesHandler
            liveserver_kwargs['static_handler'] = StaticFilesHandler
        else:
            from django.test.testcases import _StaticFilesHandler
            liveserver_kwargs['static_handler'] = _StaticFilesHandler

        if django.VERSION < (1, 11):
            host, possible_ports = parse_addr(addr)
            self.thread = LiveServerThread(host, possible_ports,
                                           **liveserver_kwargs)
        else:
            host = addr
            self.thread = LiveServerThread(host, **liveserver_kwargs)

        self._live_server_modified_settings = modify_settings(
            ALLOWED_HOSTS={'append': host},
        )
        self._live_server_modified_settings.enable()

        self.thread.daemon = True
        self.thread.start()
        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error

Example 18

Project: django-fancypages Source File: conf.py
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):

        # Grab the field list from the meta class
        fields = obj._meta.fields

        for field in fields:
            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_unicode(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_unicode(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(':param %s: %s' % (field.attname, verbose_name))

            # Add the field's type to the docstring
            lines.append(':type %s: %s' % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines

Example 19

Project: django-linguist Source File: mixins.py
    def get_queryset(self):
        from django.db import models
        QuerySet = type('LinguistQuerySet', (QuerySetMixin, models.query.QuerySet), {})
        return QuerySet(self.model)

Example 20

Project: django-nose-selenium Source File: plugins.py
Function: setup_test_db
def _setup_test_db():
    """Activates a test dbs without recreating them."""

    from django.db import connections

    for alias in connections:
        connection = connections[alias]
        connection.close()

        test_db_name = _get_test_db_name(connection)
        connection.settings_dict['NAME'] = test_db_name

        # SUPPORTS_TRANSACTIONS is not needed in newer versions of djangoo
        if not hasattr(connection.features, 'supports_transactions'):
            can_rollback = connection.creation._rollback_works()
            connection.settings_dict['SUPPORTS_TRANSACTIONS'] = can_rollback

        # Trigger side effects.
        connection.cursor()
        _set_autocommit(connection)

Example 21

Project: collab Source File: models.py
    def save(self, *args, **kwargs):
        if not self.pk and not self.slug:
            self.slug = self.slugify(self.name)
            from django.db import router
            using = kwargs.get("using") or router.db_for_write(
                type(self), instance=self)
            # Make sure we write to the same db for all attempted writes,
            # with a multi-master setup, theoretically we could try to
            # write and rollback on different DBs
            kwargs["using"] = using
            trans_kwargs = {"using": using}

            i = 0
            while True:
                i += 1
                try:
                    sid = transaction.savepoint(**trans_kwargs)
                    res = super(TagBase, self).save(*args, **kwargs)
                    transaction.savepoint_commit(sid, **trans_kwargs)
                    return res
                except IntegrityError:
                    transaction.savepoint_rollback(sid, **trans_kwargs)
                    self.slug = self.slugify(self.name, i)
        else:
            return super(TagBase, self).save(*args, **kwargs)

Example 22

Project: django-mailbox Source File: conf.py
def process_docstring(app, what, name, obj, options, lines):
    # Source: https://gist.github.com/abulka/48b54ea4cbc7eb014308
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):
        # Grab the field list from the meta class
        fields = obj._meta.get_fields()

        for field in fields:
            # Skip ManyToOneRel and ManyToManyRel fields which have no 'verbose_name' or 'help_text'
            if not hasattr(field, 'verbose_name'):
                continue

            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_text(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_text(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.attname, verbose_name))

            # Add the field's type to the docstring
            if isinstance(field, models.ForeignKey):
                to = field.rel.to
                lines.append(u':type %s: %s to :class:`~%s.%s`' % (field.attname, type(field).__name__, to.__module__, to.__name__))
            else:
                lines.append(u':type %s: %s' % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines

Example 23

Project: dissemin Source File: conf.py
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):
        # Grab the field list from the meta class
        fields = obj._meta.fields

        for field in fields:
            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_unicode(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_unicode(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.attname, verbose_name))

            # Add the field's type to the docstring
            lines.append(u':type %s: %s' %
                         (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines

Example 24

Project: django-fluent-contents Source File: docstrings.py
def improve_model_docstring(app, what, name, obj, options, lines):
    from django.db import models  # must be inside the function, to allow settings initialization first.

    if inspect.isclass(obj) and issubclass(obj, models.Model):
        if django.VERSION >= (1,8):
            model_fields = obj._meta.get_fields()
        elif django.VERSION >= (1,6):
            model_fields = obj._meta.fields
        else:
            model_fields = obj._meta._fields()

        for field in model_fields:
            help_text = strip_tags(force_unicode(field.help_text))
            verbose_name = force_unicode(field.verbose_name).capitalize()

            # Add parameter
            if help_text:
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                lines.append(u':param %s: %s' % (field.attname, verbose_name))

            # Add type
            if isinstance(field, models.ForeignKey):
                to = field.rel.to
                lines.append(u':type %s: %s to :class:`~%s.%s`' % (field.attname, type(field).__name__, to.__module__, to.__name__))
            else:
                lines.append(u':type %s: %s' % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines

Example 25

Project: django-oscar Source File: conf.py
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):

        # Ignore abstract models
        if not hasattr(obj._meta, '_fields'):
            return lines

        # Grab the field list from the meta class
        fields = obj._meta._fields()

        for field in fields:
            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_unicode(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_unicode(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.attname, verbose_name))

            # Add the field's type to the docstring
            lines.append(u':type %s: %s' % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines

Example 26

Project: evennia Source File: evennia_launcher.py
def check_database():
    """
    Check so the database exists.

    Returns:
        exists (bool): `True` if the database exists, otherwise `False`.
    """
    # Check so a database exists and is accessible
    from django.db import connection
    tables = connection.introspection.get_table_list(connection.cursor())
    if not tables or not isinstance(tables[0], basestring): # django 1.8+
        tables = [tableinfo.name for tableinfo in tables]
    if tables and u'players_playerdb' in tables:
        # database exists and seems set up. Initialize evennia.
        import evennia
        evennia._init()
    # Try to get Player#1
    from evennia.players.models import PlayerDB
    try:
        PlayerDB.objects.get(id=1)
    except django.db.utils.OperationalError as e:
        print(ERROR_DATABASE.format(traceback=e))
        sys.exit()
    except PlayerDB.DoesNotExist:
        # no superuser yet. We need to create it.

        other_superuser = PlayerDB.objects.filter(is_superuser=True)
        if other_superuser:
            # Another superuser was found, but not with id=1. This may
            # happen if using flush (the auto-id starts at a higher
            # value). Wwe copy this superuser into id=1. To do
            # this we must deepcopy it, delete it then save the copy
            # with the new id. This allows us to avoid the UNIQUE
            # constraint on usernames.
            other = other_superuser[0]
            other_id = other.id
            other_key = other.username
            print(WARNING_MOVING_SUPERUSER.format(
                other_key=other_key, other_id=other_id))
            res = ""
            while res.upper() != "Y":
                # ask for permission
                res = input("Continue [Y]/N: ")
                if res.upper() == "N":
                    sys.exit()
                elif not res:
                    break
            # continue with the
            from copy import deepcopy
            new = deepcopy(other)
            other.delete()
            new.id = 1
            new.save()
        else:
            create_superuser()
            check_database()
    return True

Example 27

Project: raven-python Source File: tests.py
    @pytest.mark.skipif(not DJANGO_15, reason='< Django 1.5')
    def test_get_user_info_abstract_user(self):
        from django.db import models
        from django.contrib.auth.models import AbstractBaseUser

        class MyUser(AbstractBaseUser):
            USERNAME_FIELD = 'username'

            username = models.CharField(max_length=32)
            email = models.EmailField()

        user = MyUser(
            username='admin',
            email='[email protected]',
            id=1,
        )
        user_info = self.raven.get_user_info(user)
        assert user_info == {
            'username': user.username,
            'id': user.id,
            'email': user.email,
        }

Example 28

Project: raven-python Source File: tests.py
    @pytest.mark.skipif(not DJANGO_110, reason='< Django 1.10')
    def test_get_user_info_is_authenticated_property(self):
        from django.db import models
        from django.contrib.auth.models import AbstractBaseUser

        class MyUser(AbstractBaseUser):
            USERNAME_FIELD = 'username'
            username = models.CharField(max_length=32)
            email = models.EmailField()

            @property
            def is_authenticated(self):
                return True

        user = MyUser(
            username='admin',
            email='[email protected]',
            id=1,
        )
        user_info = self.raven.get_user_info(user)
        assert user_info == {
            'username': user.username,
            'id': user.id,
            'email': user.email,
        }

Example 29

Project: pyamf Source File: test_django.py
    def test_undefined(self):
        from django.db import models
        from django.db.models import fields

        class UndefinedClass(models.Model):
            pass

        alias = adapter.DjangoClassAlias(UndefinedClass, None)

        x = UndefinedClass()

        alias.applyAttributes(x, {
            'id': pyamf.Undefined
        })

        self.assertEqual(x.id, fields.NOT_PROVIDED)

        x.id = fields.NOT_PROVIDED

        attrs = alias.getEncodableAttributes(x)
        self.assertEqual(attrs, {'id': pyamf.Undefined})

Example 30

Project: pyamf Source File: test_django.py
    def test_non_field_prop(self):
        from django.db import models

        class Book(models.Model):
            def _get_number_of_odd_pages(self):
                return 234

            # note the lack of a setter callable ..
            numberOfOddPages = property(_get_number_of_odd_pages)

        alias = adapter.DjangoClassAlias(Book, 'Book')

        x = Book()

        self.assertEqual(
            alias.getEncodableAttributes(x),
            {'numberOfOddPages': 234, 'id': None}
        )

        # now we test sending the numberOfOddPages attribute
        alias.applyAttributes(x, {'numberOfOddPages': 24, 'id': None})

        # test it hasn't been set
        self.assertEqual(x.numberOfOddPages, 234)

Example 31

Project: pyamf Source File: test_django.py
    def test_properties(self):
        """
        See #764
        """
        from django.db import models

        class Foob(models.Model):
            def _get_days(self):
                return 1

            def _set_days(self, val):
                assert 1 == val

            days = property(_get_days, _set_days)

        alias = adapter.DjangoClassAlias(Foob, 'Bar')

        x = Foob()

        self.assertEqual(x.days, 1)

        self.assertEqual(
            alias.getEncodableAttributes(x),
            {'days': 1, 'id': None}
        )

        # now we test sending the numberOfOddPages attribute
        alias.applyAttributes(x, {'id': None})

Example 32

Project: django-discover-runner Source File: runner.py
Function: setup_databases
def setup_databases(verbosity, interactive, **kwargs):
    from django.db import connections, DEFAULT_DB_ALIAS

    # First pass -- work out which databases actually need to be created,
    # and which ones are test mirrors or duplicate entries in DATABASES
    mirrored_aliases = {}
    test_databases = {}
    dependencies = {}
    for alias in connections:
        connection = connections[alias]
        if connection.settings_dict['TEST_MIRROR']:
            # If the database is marked as a test mirror, save
            # the alias.
            mirrored_aliases[alias] = (
                connection.settings_dict['TEST_MIRROR'])
        else:
            # Store a tuple with DB parameters that uniquely identify it.
            # If we have two aliases with the same values for that tuple,
            # we only need to create the test database once.
            item = test_databases.setdefault(
                connection.creation.test_db_signature(),
                (connection.settings_dict['NAME'], set())
            )
            item[1].add(alias)

            if 'TEST_DEPENDENCIES' in connection.settings_dict:
                dependencies[alias] = (
                    connection.settings_dict['TEST_DEPENDENCIES'])
            else:
                if alias != DEFAULT_DB_ALIAS:
                    dependencies[alias] = connection.settings_dict.get(
                        'TEST_DEPENDENCIES', [DEFAULT_DB_ALIAS])

    # Second pass -- actually create the databases.
    old_names = []
    mirrors = []

    for signature, (db_name, aliases) in dependency_ordered(
            test_databases.items(), dependencies):
        test_db_name = None
        # Actually create the database for the first connection

        for alias in aliases:
            connection = connections[alias]
            old_names.append((connection, db_name, True))
            if test_db_name is None:
                test_db_name = connection.creation.create_test_db(
                    verbosity, autoclobber=not interactive)
            else:
                connection.settings_dict['NAME'] = test_db_name

    for alias, mirror_alias in mirrored_aliases.items():
        mirrors.append((alias, connections[alias].settings_dict['NAME']))
        connections[alias].settings_dict['NAME'] = (
            connections[mirror_alias].settings_dict['NAME'])

    return old_names, mirrors

Example 33

Project: permabots Source File: conf.py
Function: process_docstring
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models
    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):

        # Ignore abstract models
        if not hasattr(obj._meta, 'fields'):
            return lines

        # Grab the field list from the meta class
        fields = obj._meta.fields
        
        for field in fields:
            # Decode and strip any html out of the field's help text
            if hasattr(field, 'help_text'):
                help_text = strip_tags(force_unicode(field.help_text))
            else:
                help_text = None

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            if hasattr(field, 'verbose_name'):
                verbose_name = force_unicode(field.verbose_name).capitalize()
            else:
                verbose_name = ""

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.attname, verbose_name))

            # Add the field's type to the docstring
            lines.append(u':type %s: %s' % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines

Example 34

Project: django-hvad Source File: ordering.py
Function: test_checks
    @minimumDjangoVersion(1, 7)
    def test_checks(self):
        from django.db import models
        from hvad.models import TranslatableModel, TranslatedFields

        class ModelWithOrdering1(TranslatableModel):
            translations = TranslatedFields(
                translated_field=models.CharField(max_length=50),
            )
            class Meta:
                ordering = ('translated_field',)
        errors = ModelWithOrdering1.check()
        self.assertFalse(errors)

        class ModelWithOrdering2(TranslatableModel):
            translations = TranslatedFields(
                translated_field=models.CharField(max_length=50),
            )
            class Meta:
                ordering = ('language_code',)
        errors = ModelWithOrdering2.check()
        self.assertTrue(errors)

Example 35

Project: kolibri Source File: conf.py
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):
        # Grab the field list from the meta class
        fields = obj._meta.get_fields()

        for field in fields:
            # Skip ManyToOneRel and ManyToManyRel fields which have no 'verbose_name' or 'help_text'
            if not hasattr(field, 'verbose_name'):
                continue

            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_text(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_text(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.attname, verbose_name))

            # Add the field's type to the docstring
            if isinstance(field, models.ForeignKey):
                to = field.rel.to
                lines.append(u':type %s: %s to :class:`~%s`' % (field.attname, type(field).__name__, to))
            else:
                lines.append(u':type %s: %s' % (field.attname, type(field).__name__))

    return lines