django.db.models.CharField

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

135 Examples 7

Example 101

Project: django Source File: tests.py
    @cxOracle_py3_bug
    def test_custom_functions_can_ref_other_functions(self):
        Company(name='Apple', motto=None, ticker_name='APPL', description='Beautiful Devices').save()
        Company(name='Django Software Foundation', motto=None, ticker_name=None, description=None).save()
        Company(name='Google', motto='Do No Evil', ticker_name='GOOG', description='Internet Company').save()
        Company(name='Yahoo', motto=None, ticker_name=None, description='Internet Company').save()

        class Lower(Func):
            function = 'LOWER'

        qs = Company.objects.annotate(
            tagline=Func(
                F('motto'),
                F('ticker_name'),
                F('description'),
                Value('No Tag'),
                function='COALESCE')
        ).annotate(
            tagline_lower=Lower(F('tagline'), output_field=CharField())
        ).order_by('name')

        # LOWER function supported by:
        # oracle, postgres, mysql, sqlite, sqlserver

        self.assertQuerysetEqual(
            qs, [
                ('Apple', 'APPL'.lower()),
                ('Django Software Foundation', 'No Tag'.lower()),
                ('Google', 'Do No Evil'.lower()),
                ('Yahoo', 'Internet Company'.lower())
            ],
            lambda c: (c.name, c.tagline_lower)
        )

Example 102

Project: django-denorm Source File: models.py
Function: author_name
    @denormalized(models.CharField, max_length=255)
    @depend_on_related('Post')
    def author_name(self):
        return post.author.name

Example 103

Project: django-denorm Source File: models.py
Function: full_name
    @denormalized(models.CharField, max_length=255)
    def full_name(self):
        return u"%s %s" % (self.first_name, self.name)

Example 104

Project: django-leonardo Source File: models.py
Function: initialize_type
    @classmethod
    def initialize_type(cls, APPLICATIONS):
        for i in APPLICATIONS:
            if not 2 <= len(i) <= 3:
                raise ValueError(
                    "APPLICATIONS must be provided with tuples containing at"
                    " least two parameters (urls, name) and an optional extra"
                    " config dict")

            urls, name = i[0:2]

            if len(i) == 3:
                app_conf = i[2]

                if not isinstance(app_conf, dict):
                    raise ValueError(
                        "The third parameter of an APPLICATIONS entry must be"
                        " a dict or the name of one!")
            else:
                app_conf = {}

            cls.ALL_APPS_CONFIG[urls] = {
                "urls": urls,
                "name": name,
                "config": app_conf
            }

        cls.add_to_class(
            'urlconf_path',
            models.CharField(_('application'), max_length=100, choices=[
                (c['urls'], c['name']) for c in cls.ALL_APPS_CONFIG.values()])
        )

        class ApplicationContentItemEditorForm(WidgetUpdateForm):
            app_config = {}
            custom_fields = {}

            def __init__(self, *args, **kwargs):
                super(ApplicationContentItemEditorForm, self).__init__(
                    *args, **kwargs)

                instance = kwargs.get("instance", None)

                if instance:
                    try:
                        # TODO use urlconf_path from POST if set
                        # urlconf_path = request.POST.get('...urlconf_path',
                        #     instance.urlconf_path)
                        self.app_config = cls.ALL_APPS_CONFIG[
                            instance.urlconf_path]['config']
                    except KeyError:
                        self.app_config = {}

                    self.custom_fields = {}
                    admin_fields = self.app_config.get('admin_fields', {})

                    if isinstance(admin_fields, dict):
                        self.custom_fields.update(admin_fields)
                    else:
                        get_fields = get_object(admin_fields)
                        self.custom_fields.update(
                            get_fields(self, *args, **kwargs))

                    params = self.instance.parameters
                    for k, v in self.custom_fields.items():
                        v.initial = params.get(k)
                        self.fields[k] = v
                        if k in params:
                            self.fields[k].initial = params[k]

Example 105

Project: django-dbindexer Source File: backends.py
Function: create_index
    def create_index(self, lookup):
        field_to_index = self.get_field_to_index(lookup.model, lookup.field_name)

        # backend doesn't now how to handle this index definition
        if not field_to_index:
            return

        index_field = lookup.get_field_to_add(field_to_index)
        config_field = index_field.item_field if \
            isinstance(index_field, ListField) else index_field
        if field_to_index.max_length is not None and \
                isinstance(config_field, models.CharField):
            config_field.max_length = field_to_index.max_length

        if isinstance(field_to_index,
            (models.DateField, models.DateTimeField, models.TimeField)):
            if field_to_index.auto_now or field_to_index.auto_now_add:
                raise ImproperlyConfigured('\'auto_now\' and \'auto_now_add\' '
                    'on %s.%s is not supported by dbindexer.' %
                    (lookup.model._meta.object_name, lookup.field_name))

        # don't install a field if it already exists
        try:
            lookup.model._meta.get_field(self.index_name(lookup))
        except:
            lookup.model.add_to_class(self.index_name(lookup), index_field)
            self.index_map[lookup] = index_field
            self.add_column_to_name(lookup.model, lookup.field_name)
        else:
            # makes dbindexer unit test compatible
            if lookup not in self.index_map:
                self.index_map[lookup] = lookup.model._meta.get_field(
                    self.index_name(lookup))
                self.add_column_to_name(lookup.model, lookup.field_name)

Example 106

Project: nonrel-search Source File: core.py
Function: init
    def __init__(self, search_manager, *args, **kwargs):
        self.search_manager = search_manager
        kwargs['item_field'] = models.CharField(max_length=500)
        kwargs['editable'] = False
        super(IndexField, self).__init__(*args, **kwargs)

Example 107

Project: django-rest-framework-hstore Source File: serializers.py
Function: build_standard_field
    def build_standard_field(self, field_name, model_field):
        """
        Creates a default instance of a basic non-relational field.
        """
        kwargs = {}

        if model_field.null or model_field.blank:
            kwargs['required'] = False

            if model_field.null:
                kwargs['allow_null'] = True
            if model_field.blank and (issubclass(model_field.__class__, models.CharField) or
                                      (issubclass(model_field.__class__, models.TextField))):
                kwargs['allow_blank'] = True

        if isinstance(model_field, models.AutoField) or not model_field.editable:
            kwargs['read_only'] = True

        if model_field.has_default():
            kwargs['default'] = model_field.get_default()

        if issubclass(model_field.__class__, models.TextField):
            kwargs['style'] = {'base_template': 'textarea.html'}

        if model_field.verbose_name is not None:
            kwargs['label'] = model_field.verbose_name

        if model_field.help_text is not None:
            kwargs['help_text'] = model_field.help_text

        # TODO: TypedChoiceField?
        if model_field.flatchoices:  # This ModelField contains choices
            kwargs['choices'] = model_field.flatchoices
            if model_field.null:
                kwargs['empty'] = None
            return (ChoiceField, kwargs)

        # put this below the ChoiceField because min_value isn't a valid initializer
        if issubclass(model_field.__class__, models.PositiveIntegerField) or\
                issubclass(model_field.__class__, models.PositiveSmallIntegerField):
            kwargs['min_value'] = 0

        attribute_dict = {
            models.CharField: ['max_length'],
            models.CommaSeparatedIntegerField: ['max_length'],
            models.DecimalField: ['max_digits', 'decimal_places'],
            models.EmailField: ['max_length'],
            models.FileField: ['max_length'],
            models.ImageField: ['max_length'],
            models.SlugField: ['max_length'],
            models.URLField: ['max_length'],
        }

        # === django-rest-framework-hstore specific ====
        # if available, use __basefield__ attribute instead of __class__
        # this will cause DRF to pick the correct DRF-field
        key = getattr(model_field, '__basefield__', model_field.__class__)

        if key in attribute_dict:
            attributes = attribute_dict[key]
            for attribute in attributes:
                kwargs.update({attribute: getattr(model_field, attribute)})

        if model_field.__class__ == DictionaryField and model_field.schema:
            kwargs['schema'] = True

        try:
            return (self.serializer_field_mapping[key], kwargs)
        except KeyError:
            pass

        try:
            return (self.serializer_field_mapping[model_field.__class__.__name__], kwargs)
        except KeyError:
            # return ModelField(model_field=model_field, **kwargs)
            return super(HStoreSerializer, self).build_standard_field(field_name, model_field)

Example 108

Project: django-pg-fts Source File: fields.py
Function: check
    def check(self, **kwargs):
        errors = super(TSVectorField, self).check(**kwargs)
        for f in self.fields:
            field = None
            if isinstance(f, (tuple, list)):
                if len(f) > 2:
                    errors.append(
                        checks.Error(
                            'Invalid value in fields "%s"' % (str(f),),
                            hint='can be "field" or ("field", "rank")',
                            obj=self,
                            id='fts.E001'
                        )
                    )
                else:
                    field = f[0]
                    if f[1].upper() not in self.RANK_LEVELS:
                        errors.append(
                            checks.Error(
                                'Invalid rank "%s" in "%s"' % (str(f[1]), f),
                                hint=('Available ranks %s' %
                                      ' or '.join(self.RANK_LEVELS)),
                                obj=self,
                                id='fts.E001'
                            )
                        )
            else:
                field = f
            if field and not isinstance(field, six.string_types):
                errors.append(
                    checks.Error(
                        'Invalid value in fields "%s"' % (str(f),),
                        hint='can be name of field or (field, rank)',
                        obj=self,
                        id='fts.E001'
                    )
                )
            elif field:
                try:
                    t = self.model._meta.get_field_by_name(field)[0]
                    if not isinstance(t, (models.CharField, models.TextField)):
                        errors.append(
                            checks.Error(
                                'Field must be CharField or TextField.',
                                hint=None,
                                obj=self,
                                id='fts.E001'
                            )
                        )
                except models.FieldDoesNotExist:
                    errors.append(
                        checks.Error(
                            'FieldDoesNotExistFieldDoesNotExist %s' % str(f),
                            hint=None,
                            obj=self,
                            id='fts.E001'
                        )
                    )

        return errors

Example 109

Project: idios Source File: middleware.py
@csrf_protect
def handle_additional_info(request):
    if request.user.is_authenticated():
        profile = request.user.get_profile()
        missing_fields = []
        # look for fields which are required on the model
        for field in profile.idios_required_fields():
            name = isinstance(field, tuple) and field[0] or field
            db_field = profile._meta.get_field(name)
            value = getattr(profile, db_field.attname)
            if isinstance(db_field, (models.CharField, models.TextField)):
                missing = not value
            else:
                missing = value is None
            if missing:
                if not isinstance(field, tuple):
                    missing_fields.append((field, db_field.formfield()))
                else:
                    missing_fields.append(field)
        if not missing_fields:
            return None
        attrs = {}
        for field in missing_fields:
            attrs[field[0]] = field[1]
        AdditionalInfoForm = type("AdditionalInfoForm", (forms.Form,), attrs)
        if request.method == "POST":
            form = AdditionalInfoForm(request.POST, request.FILES)
            if form.is_valid():
                request.session.pop("idios_additional_info_kickstart", None)
                for field, value in form.cleaned_data.iteritems():
                    setattr(profile, field, value)
                profile.save()
                return redirect(request.path)
        else:
            form = AdditionalInfoForm()
        ctx = {
            "form": form,
        }
        return render_to_response(
            "idios/additional_info.html",
            RequestContext(request, ctx)
        )

Example 110

Project: django-reversion Source File: models.py
def _safe_subquery(method, left_query, left_field_name, right_subquery, right_field_name):
    right_subquery = right_subquery.order_by().values_list(right_field_name, flat=True)
    left_field = left_query.model._meta.get_field(left_field_name)
    right_field = right_subquery.model._meta.get_field(right_field_name)
    # If the databases don't match, we have to do it in-memory.
    # If it's not a supported database, we also have to do it in-memory.
    if (
        left_query.db != right_subquery.db or not
        (
            left_field.get_internal_type() != right_field.get_internal_type() and
            connections[left_query.db].vendor in ("sqlite", "postgresql")
        )
    ):
        right_subquery = list(right_subquery.iterator())
    else:
        # If the left hand side is not a text field, we need to cast it.
        if not isinstance(left_field, (models.CharField, models.TextField)):
            left_field_name_str = "{}_str".format(left_field_name)
            left_query = left_query.annotate(**{
                left_field_name_str: _Str(left_field_name),
            })
            left_field_name = left_field_name_str
        # If the right hand side is not a text field, we need to cast it.
        if not isinstance(right_field, (models.CharField, models.TextField)):
            right_field_name_str = "{}_str".format(right_field_name)
            right_subquery = right_subquery.annotate(**{
                right_field_name_str: _Str(right_field_name),
            }).values_list(right_field_name_str, flat=True)
    # All done!
    return getattr(left_query, method)(**{
        "{}__in".format(left_field_name): right_subquery,
    })

Example 111

Project: django-watson Source File: search.py
Function: get_content
    def get_content(self, obj):
        """
        Returns the content of this search result.
        This is given low priority in search result ranking.

        You can access the content of the search entry as `entry.content` in your search results,
        although this field generally contains a big mess of search data so is less suitable
        for frontend display.

        The default implementation returns all the registered fields in your model joined together.
        """
        # Get the field names to look up.
        field_names = self.fields or (
            field.name for field in self.model._meta.fields if
            isinstance(field, (models.CharField, models.TextField))
        )
        # Exclude named fields.
        field_names = (field_name for field_name in field_names if field_name not in self.exclude)
        # Create the text.
        return self.prepare_content(" ".join(
            force_text(self._resolve_field(obj, field_name))
            for field_name in field_names
        ))

Example 112

Project: feincms Source File: models.py
    @classmethod
    def initialize_type(cls, APPLICATIONS):
        for i in APPLICATIONS:
            if not 2 <= len(i) <= 3:
                raise ValueError(
                    "APPLICATIONS must be provided with tuples containing at"
                    " least two parameters (urls, name) and an optional extra"
                    " config dict")

            urls, name = i[0:2]

            if len(i) == 3:
                app_conf = i[2]

                if not isinstance(app_conf, dict):
                    raise ValueError(
                        "The third parameter of an APPLICATIONS entry must be"
                        " a dict or the name of one!")
            else:
                app_conf = {}

            cls.ALL_APPS_CONFIG[urls] = {
                "urls": urls,
                "name": name,
                "config": app_conf
            }

        cls.add_to_class(
            'urlconf_path',
            models.CharField(_('application'), max_length=100, choices=[
                (c['urls'], c['name']) for c in cls.ALL_APPS_CONFIG.values()])
        )

        class ApplicationContentItemEditorForm(ItemEditorForm):
            app_config = {}
            custom_fields = {}

            def __init__(self, *args, **kwargs):
                super(ApplicationContentItemEditorForm, self).__init__(
                    *args, **kwargs)

                instance = kwargs.get("instance", None)

                if instance:
                    try:
                        # TODO use urlconf_path from POST if set
                        # urlconf_path = request.POST.get('...urlconf_path',
                        #     instance.urlconf_path)
                        self.app_config = cls.ALL_APPS_CONFIG[
                            instance.urlconf_path]['config']
                    except KeyError:
                        self.app_config = {}

                    self.custom_fields = {}
                    admin_fields = self.app_config.get('admin_fields', {})

                    if isinstance(admin_fields, dict):
                        self.custom_fields.update(admin_fields)
                    else:
                        get_fields = get_object(admin_fields)
                        self.custom_fields.update(
                            get_fields(self, *args, **kwargs))

                    params = self.instance.parameters
                    for k, v in self.custom_fields.items():
                        v.initial = params.get(k)
                        self.fields[k] = v
                        if k in params:
                            self.fields[k].initial = params[k]

            def save(self, commit=True, *args, **kwargs):
                # Django ModelForms return the model instance from save. We'll
                # call save with commit=False first to do any necessary work &
                # get the model so we can set .parameters to the values of our
                # custom fields before calling save(commit=True)

                m = super(ApplicationContentItemEditorForm, self).save(
                    commit=False, *args, **kwargs)

                m.parameters = dict(
                    (k, self.cleaned_data[k])
                    for k in self.custom_fields if k in self.cleaned_data)

                if commit:
                    m.save(**kwargs)

                return m

        # This provides hooks for us to customize the admin interface for
        # embedded instances:
        cls.feincms_item_editor_form = ApplicationContentItemEditorForm

Example 113

Project: feincms Source File: translations.py
Function: handle_model
    def handle_model(self):
        cls = self.model

        cls.add_to_class(
            'language',
            models.CharField(
                _('language'),
                max_length=10,
                choices=django_settings.LANGUAGES,
                default=django_settings.LANGUAGES[0][0]))
        cls.add_to_class(
            'translation_of',
            models.ForeignKey(
                'self',
                blank=True, null=True, verbose_name=_('translation of'),
                related_name='translations',
                limit_choices_to={'language': django_settings.LANGUAGES[0][0]},
                help_text=_(
                    'Leave this empty for entries in the primary language.'),
            )
        )

        if hasattr(cls, 'register_request_processor'):
            if settings.FEINCMS_TRANSLATION_POLICY == "EXPLICIT":
                cls.register_request_processor(
                    translations_request_processor_explicit,
                    key='translations')
            else:  # STANDARD
                cls.register_request_processor(
                    translations_request_processor_standard,
                    key='translations')

        if hasattr(cls, 'get_redirect_to_target'):
            original_get_redirect_to_target = cls.get_redirect_to_target

            @monkeypatch_method(cls)
            def get_redirect_to_target(self, request=None):
                """
                Find an acceptable redirect target. If this is a local link,
                then try to find the page this redirect references and
                translate it according to the user's language. This way, one
                can easily implement a localized "/"-url to welcome page
                redirection.
                """
                target = original_get_redirect_to_target(self, request)
                if target and target.find('//') == -1:
                    # Not an offsite link http://bla/blubb
                    try:
                        page = cls.objects.page_for_path(target)
                        language = get_current_language_code(request)
                        language = translation_allowed_language(language)
                        page = page.get_translation(language)
                        # Note: Does not care about active status?
                        target = page.get_absolute_url()
                    except cls.DoesNotExist:
                        pass
                return target

        @monkeypatch_method(cls)
        def available_translations(self):
            if not self.id:  # New, unsaved pages have no translations
                return []

            if hasattr(cls.objects, 'apply_active_filters'):
                filter_active = cls.objects.apply_active_filters
            else:
                def filter_active(queryset):
                    return queryset

            if is_primary_language(self.language):
                return filter_active(self.translations.all())
            elif self.translation_of:
                # reuse prefetched queryset, do not filter it
                res = [
                    t for t
                    in filter_active(self.translation_of.translations.all())
                    if t.language != self.language]
                res.insert(0, self.translation_of)
                return res
            else:
                return []

        @monkeypatch_method(cls)
        def get_original_translation(self, *args, **kwargs):
            if is_primary_language(self.language):
                return self
            if self.translation_of:
                return self.translation_of
            logger.debug(
                "Page pk=%d (%s) has no primary language translation (%s)",
                self.pk, self.language, django_settings.LANGUAGES[0][0])
            return self

        @monkeypatch_property(cls)
        def original_translation(self):
            return self.get_original_translation()

        @monkeypatch_method(cls)
        def get_translation(self, language):
            return self.original_translation.translations.get(
                language=language)

Example 114

Project: feincms Source File: models.py
def create_base_model(inherit_from=models.Model):
    """
    This method can  be used to create a FeinCMS base model inheriting from
    your own custom subclass (f.e. extend ``MPTTModel``). The default is to
    extend :class:`django.db.models.Model`.
    """

    class Base(inherit_from, ExtensionsMixin):
        """
        This is the base class for your CMS models. It knows how to create and
        manage content types.
        """

        class Meta:
            abstract = True

        _cached_django_content_type = None

        @classmethod
        def register_regions(cls, *regions):
            """
            Register a list of regions. Only use this if you do not want to use
            multiple templates with this model (read: not use
            ``register_templates``)::

                BlogEntry.register_regions(
                    ('main', _('Main content area')),
                    )
            """

            if hasattr(cls, 'template'):
                warnings.warn(
                    'Ignoring second call to register_regions.',
                    RuntimeWarning)
                return

            # implicitly creates a dummy template object -- the item editor
            # depends on the presence of a template.
            cls.template = Template('', '', regions)
            cls._feincms_all_regions = cls.template.regions

        @classmethod
        def register_templates(cls, *templates):
            """
            Register templates and add a ``template_key`` field to the model
            for saving the selected template::

                Page.register_templates({
                    'key': 'base',
                    'title': _('Standard template'),
                    'path': 'feincms_base.html',
                    'regions': (
                        ('main', _('Main content area')),
                        ('sidebar', _('Sidebar'), 'inherited'),
                        ),
                    }, {
                    'key': '2col',
                    'title': _('Template with two columns'),
                    'path': 'feincms_2col.html',
                    'regions': (
                        ('col1', _('Column one')),
                        ('col2', _('Column two')),
                        ('sidebar', _('Sidebar'), 'inherited'),
                        ),
                    })
            """

            if not hasattr(cls, '_feincms_templates'):
                cls._feincms_templates = OrderedDict()
                cls.TEMPLATES_CHOICES = []

            instances = cls._feincms_templates

            for template in templates:
                if not isinstance(template, Template):
                    template = Template(**template)

                instances[template.key] = template

            try:
                field = next(iter(
                    field for field in cls._meta.local_fields
                    if field.name == 'template_key'))
            except (StopIteration,):
                cls.add_to_class(
                    'template_key',
                    models.CharField(_('template'), max_length=255, choices=(
                        # Dummy choice to trick Django. Cannot be empty,
                        # otherwise admin.E023 happens.
                        ('__dummy', '__dummy'),
                    ))
                )
                field = next(iter(
                    field for field in cls._meta.local_fields
                    if field.name == 'template_key'))

                def _template(self):
                    ensure_completely_loaded()

                    try:
                        return self._feincms_templates[self.template_key]
                    except KeyError:
                        # return first template as a fallback if the template
                        # has changed in-between
                        return self._feincms_templates[
                            list(self._feincms_templates.keys())[0]]

                cls.template = property(_template)

            cls.TEMPLATE_CHOICES = [
                (template_.key, template_.title,)
                for template_ in cls._feincms_templates.values()
            ]
            try:
                # noqa https://github.com/django/django/commit/80e3444eca045799cc40e50c92609e852a299d38
                # Django 1.9 uses this code
                field.choices = cls.TEMPLATE_CHOICES
            except AttributeError:
                # Older versions of Django use that.
                field._choices = cls.TEMPLATE_CHOICES
            field.default = cls.TEMPLATE_CHOICES[0][0]

            # Build a set of all regions used anywhere
            cls._feincms_all_regions = set()
            for template in cls._feincms_templates.values():
                cls._feincms_all_regions.update(template.regions)

        #: ``ContentProxy`` class this object uses to collect content blocks
        content_proxy_class = ContentProxy

        @property
        def content(self):
            """
            Instantiate and return a ``ContentProxy``. You can use your own
            custom ``ContentProxy`` by assigning a different class to the
            ``content_proxy_class`` member variable.
            """

            if not hasattr(self, '_content_proxy'):
                self._content_proxy = self.content_proxy_class(self)

            return self._content_proxy

        @classmethod
        def _create_content_base(cls):
            """
            This is purely an internal method. Here, we create a base class for
            the concrete content types, which are built in
            ``create_content_type``.

            The three fields added to build a concrete content type class/model
            are ``parent``, ``region`` and ``ordering``.
            """

            # We need a template, because of the possibility of restricting
            # content types to a subset of all available regions. Each region
            # object carries a list of all allowed content types around.
            # Content types created before a region is initialized would not be
            # available in the respective region; we avoid this problem by
            # raising an ImproperlyConfigured exception early.
            cls._needs_templates()

            class Meta:
                abstract = True
                app_label = cls._meta.app_label
                ordering = ['ordering']

            def __str__(self):
                return (
                    '%s<pk=%s, parent=%s<pk=%s, %s>, region=%s,'
                    ' ordering=%d>') % (
                    self.__class__.__name__,
                    self.pk,
                    self.parent.__class__.__name__,
                    self.parent.pk,
                    self.parent,
                    self.region,
                    self.ordering)

            def render(self, **kwargs):
                """
                Default render implementation, tries to call a method named
                after the region key before giving up.

                You'll probably override the render method itself most of the
                time instead of adding region-specific render methods.
                """

                render_fn = getattr(self, 'render_%s' % self.region, None)

                if render_fn:
                    return render_fn(**kwargs)

                raise NotImplementedError

            def get_queryset(cls, filter_args):
                return cls.objects.select_related().filter(filter_args)

            attrs = {
                # The basic content type is put into
                # the same module as the CMS base type.
                # If an app_label is not given, Django
                # needs to know where a model comes
                # from, therefore we ensure that the
                # module is always known.
                '__module__': cls.__module__,
                '__str__': __str__,
                'render': render,
                'get_queryset': classmethod(get_queryset),
                'Meta': Meta,
                'parent': models.ForeignKey(cls, related_name='%(class)s_set'),
                'region': models.CharField(max_length=255),
                'ordering': models.IntegerField(_('ordering'), default=0),
            }

            # create content base type and save reference on CMS class

            name = '_Internal%sContentTypeBase' % cls.__name__
            if hasattr(sys.modules[cls.__module__], name):
                warnings.warn(
                    'The class %s.%s has the same name as the class that '
                    'FeinCMS auto-generates based on %s.%s. To avoid database'
                    'errors and import clashes, rename one of these classes.'
                    % (cls.__module__, name, cls.__module__, cls.__name__),
                    RuntimeWarning)

            cls._feincms_content_model = python_2_unicode_compatible(
                type(str(name), (models.Model,), attrs))

            # list of concrete content types
            cls._feincms_content_types = []

            # list of concrete content types having methods which may be called
            # before or after rendering the content:
            #
            # def process(self, request, **kwargs):
            #     May return a response early to short-circuit the
            #     request-response cycle
            #
            # def finalize(self, request, response)
            #     May modify the response or replace it entirely by returning
            #     a new one
            #
            cls._feincms_content_types_with_process = []
            cls._feincms_content_types_with_finalize = []

            # list of item editor context processors, will be extended by
            # content types
            if hasattr(cls, 'feincms_item_editor_context_processors'):
                cls.feincms_item_editor_context_processors = list(
                    cls.feincms_item_editor_context_processors)
            else:
                cls.feincms_item_editor_context_processors = []

            # list of templates which should be included in the item editor,
            # will be extended by content types
            if hasattr(cls, 'feincms_item_editor_includes'):
                cls.feincms_item_editor_includes = dict(
                    cls.feincms_item_editor_includes)
            else:
                cls.feincms_item_editor_includes = {}

        @classmethod
        def create_content_type(cls, model, regions=None, class_name=None,
                                **kwargs):
            """
            This is the method you'll use to create concrete content types.

            If the CMS base class is ``page.models.Page``, its database table
            will be ``page_page``. A concrete content type which is created
            from ``ImageContent`` will use ``page_page_imagecontent`` as its
            table.

            If you want a content type only available in a subset of regions,
            you can pass a list/tuple of region keys as ``regions``. The
            content type will only appear in the corresponding tabs in the item
            editor.

            If you use two content types with the same name in the same module,
            name clashes will happen and the content type created first will
            shadow all subsequent content types. You can work around it by
            specifying the content type class name using the ``class_name``
            argument. Please note that this will have an effect on the entries
            in ``django_content_type``, on ``related_name`` and on the table
            name used and should therefore not be changed after running
            ``syncdb`` for the first time.

            Name clashes will also happen if a content type has defined a
            relationship and you try to register that content type to more than
            one Base model (in different modules).  Django will raise an error
            when it tries to create the backward relationship. The solution to
            that problem is, as shown above, to specify the content type class
            name with the ``class_name`` argument.

            If you register a content type to more than one Base class, it is
            recommended to always specify a ``class_name`` when registering it
            a second time.

            You can pass additional keyword arguments to this factory function.
            These keyword arguments will be passed on to the concrete content
            type, provided that it has a ``initialize_type`` classmethod. This
            is used f.e. in ``MediaFileContent`` to pass a set of possible
            media positions (f.e. left, right, centered) through to the content
            type.
            """

            if not class_name:
                class_name = model.__name__

            # prevent double registration and registration of two different
            # content types with the same class name because of related_name
            # clashes
            try:
                getattr(cls, '%s_set' % class_name.lower())
                warnings.warn(
                    'Cannot create content type using %s.%s for %s.%s,'
                    ' because %s_set is already taken.' % (
                        model.__module__, class_name,
                        cls.__module__, cls.__name__,
                        class_name.lower()),
                    RuntimeWarning)
                return
            except AttributeError:
                # everything ok
                pass

            if not model._meta.abstract:
                raise ImproperlyConfigured(
                    'Cannot create content type from'
                    ' non-abstract model (yet).')

            if not hasattr(cls, '_feincms_content_model'):
                cls._create_content_base()

            feincms_content_base = cls._feincms_content_model

            class Meta(feincms_content_base.Meta):
                db_table = '%s_%s' % (cls._meta.db_table, class_name.lower())
                verbose_name = model._meta.verbose_name
                verbose_name_plural = model._meta.verbose_name_plural
                permissions = model._meta.permissions

            attrs = {
                # put the concrete content type into the
                # same module as the CMS base type; this is
                # necessary because 1. Django needs to know
                # the module where a model lives and 2. a
                # content type may be used by several CMS
                # base models at the same time (f.e. in
                # the blog and the page module).
                '__module__': cls.__module__,
                'Meta': Meta,
            }

            new_type = type(
                str(class_name),
                (model, feincms_content_base,),
                attrs,
            )
            cls._feincms_content_types.append(new_type)

            if hasattr(getattr(new_type, 'process', None), '__call__'):
                cls._feincms_content_types_with_process.append(new_type)
            if hasattr(getattr(new_type, 'finalize', None), '__call__'):
                cls._feincms_content_types_with_finalize.append(new_type)

            # content types can be limited to a subset of regions
            if not regions:
                regions = set([
                    region.key for region in cls._feincms_all_regions])

            for region in cls._feincms_all_regions:
                if region.key in regions:
                    region._content_types.append(new_type)

            # Add a list of CMS base types for which a concrete content type
            # has been created to the abstract content type. This is needed
            # f.e. for the update_rsscontent management command, which needs to
            # find all concrete RSSContent types, so that the RSS feeds can be
            # fetched
            if not hasattr(model, '_feincms_content_models'):
                model._feincms_content_models = []

            model._feincms_content_models.append(new_type)

            # Add a backlink from content-type to content holder class
            new_type._feincms_content_class = cls

            # Handle optgroup argument for grouping content types in the item
            # editor
            optgroup = kwargs.pop('optgroup', None)
            if optgroup:
                new_type.optgroup = optgroup

            # customization hook.
            if hasattr(new_type, 'initialize_type'):
                new_type.initialize_type(**kwargs)
            else:
                for k, v in kwargs.items():
                    setattr(new_type, k, v)

            # collect item editor context processors from the content type
            if hasattr(model, 'feincms_item_editor_context_processors'):
                cls.feincms_item_editor_context_processors.extend(
                    model.feincms_item_editor_context_processors)

            # collect item editor includes from the content type
            if hasattr(model, 'feincms_item_editor_includes'):
                for key, incls in model.feincms_item_editor_includes.items():
                    cls.feincms_item_editor_includes.setdefault(
                        key, set()).update(incls)

            ensure_completely_loaded(force=True)
            return new_type

        @property
        def _django_content_type(self):
            if not getattr(self, '_cached_django_content_type', None):
                self.__class__._cached_django_content_type = (
                    ContentType.objects.get_for_model(self))
            return self.__class__._cached_django_content_type

        @classmethod
        def content_type_for(cls, model):
            """
            Return the concrete content type for an abstract content type::

                from feincms.content.video.models import VideoContent
                concrete_type = Page.content_type_for(VideoContent)
            """

            if (not hasattr(cls, '_feincms_content_types') or
                    not cls._feincms_content_types):
                return None

            for type in cls._feincms_content_types:
                if issubclass(type, model):
                    if type.__base__ is model:
                        return type
            return None

        @classmethod
        def _needs_templates(cls):
            ensure_completely_loaded()

            # helper which can be used to ensure that either register_regions
            # or register_templates has been executed before proceeding
            if not hasattr(cls, 'template'):
                raise ImproperlyConfigured(
                    'You need to register at least one'
                    ' template or one region on %s.' % cls.__name__)

        @classmethod
        def _needs_content_types(cls):
            ensure_completely_loaded()

            # Check whether any content types have been created for this base
            # class
            if not getattr(cls, '_feincms_content_types', None):
                raise ImproperlyConfigured(
                    'You need to create at least one'
                    ' content type for the %s model.' % cls.__name__)

        def copy_content_from(self, obj):
            """
            Copy all content blocks over to another CMS base object. (Must be
            of the same type, but this is not enforced. It will crash if you
            try to copy content from another CMS base type.)
            """

            for cls in self._feincms_content_types:
                for content in cls.objects.filter(parent=obj):
                    new = copy_model_instance(
                        content, exclude=('id', 'parent'))
                    new.parent = self
                    new.save()

        def replace_content_with(self, obj):
            """
            Replace the content of the current object with content of another.

            Deletes all content blocks and calls ``copy_content_from``
            afterwards.
            """

            for cls in self._feincms_content_types:
                cls.objects.filter(parent=self).delete()
            self.copy_content_from(obj)

        @classmethod
        def register_with_reversion(cls):
            try:
                from reversion.revisions import register
            except ImportError:
                try:
                    from reversion import register
                except ImportError:
                    raise EnvironmentError("django-reversion is not installed")

            follow = []
            for content_type in cls._feincms_content_types:
                follow.append('%s_set' % content_type.__name__.lower())
                register(content_type)
            register(cls, follow=follow)

    return Base

Example 115

Project: django-cryptography Source File: test_encrypted.py
Function: test_deconstruct_args
    def test_deconstruct_args(self):
        field = encrypt(models.CharField(max_length=20))
        name, path, args, kwargs = field.deconstruct()
        new = encrypt(*args, **kwargs)
        self.assertEqual(new.max_length, field.max_length)

Example 116

Project: django-model-i18n Source File: translator.py
    def create_translation_model(self, master_model, opts):
        """
        Creates a model for storing `master_model`'s translations based on
        given registration options class.
        """
        attrs = {'__module__': master_model.__module__}

        class Meta:
            app_label = master_model._meta.app_label
            db_table = opts.db_table
        attrs['Meta'] = Meta

        class TranslationMeta:
            default_language = opts.default_language
            master_language = opts.master_language
            translatable_fields = opts.fields
            language_field_name = opts.language_field_name
            master_field_name = opts.master_field_name
            related_name = opts.related_name
        attrs['_transmeta'] = TranslationMeta

        # Common translation model fields
        common_fields = {
            # Translation language
            opts.language_field_name: models.CharField(db_index=True,
                verbose_name=_('language'), max_length=10,
                choices=settings.LANGUAGES),
            # Master instance FK
            opts.master_field_name: models.ForeignKey(master_model,
                verbose_name=_('master'), related_name=opts.related_name),
        }
        attrs.update(common_fields)

        # Add translatable fields
        model_name = master_model.__name__ + 'Translation'
        for field in master_model._meta.fields:
            if field.name not in opts.fields:
                continue
            if field.name in common_fields:
                raise ImproperlyConfigured, ('%s: %s field name "%s" conflicts '
                    'with the language or master FK common fields, try '
                    'changing language_field_name or master_field_name '
                    'ModelTranslation option.'
                    % (model_name, master_model.__name__, field.attname))
            newfield = copy.copy(field)
            newfield.primary_key = False
            newfield._unique = False # FIXME (unique_together)

            attrs[newfield.name] = newfield
        # setup i18n languages on master model for easier access
        master_model.i18n_languages = settings.LANGUAGES
        master_model.i18n_default_language = opts.master_language
        return type(model_name, (models.Model,), attrs)

Example 117

Project: synnefo Source File: 0015_auto__add_chain__add_project__add_projectmembership__add_unique_projec.py
    def backwards(self, orm):

        # Removing index on 'Service', fields ['name']
        db.delete_index('im_service', ['name'])

        # Removing unique constraint on 'ProjectApplication', fields ['chain', 'id']
        db.delete_unique('im_projectapplication', ['chain', 'id'])

        # Removing unique constraint on 'PendingThirdPartyUser', fields ['provider', 'third_party_identifier']
        db.delete_unique('im_pendingthirdpartyuser', ['provider', 'third_party_identifier'])

        # Removing unique constraint on 'ProjectResourceGrant', fields ['resource', 'project_application']
        db.delete_unique('im_projectresourcegrant', ['resource_id', 'project_application_id'])

        # Removing unique constraint on 'AstakosUserQuota', fields ['resource', 'user']
        db.delete_unique('im_astakosuserquota', ['resource_id', 'user_id'])

        # Removing unique constraint on 'Resource', fields ['name', 'service']
        db.delete_unique('im_resource', ['name', 'service_id'])

        # Removing unique constraint on 'AstakosUserAuthProvider', fields ['identifier', 'module', 'user']
        db.delete_unique('im_astakosuserauthprovider', ['identifier', 'module', 'user_id'])

        # Removing unique constraint on 'ProjectMembership', fields ['person', 'project']
        db.delete_unique('im_projectmembership', ['person_id', 'project_id'])

        # Deleting model 'Chain'
        db.delete_table('im_chain')

        # Deleting model 'Project'
        db.delete_table('im_project')

        # Deleting model 'ProjectMembership'
        db.delete_table('im_projectmembership')

        # Deleting model 'ResourceMetadata'
        db.delete_table('im_resourcemetadata')

        # Deleting model 'AstakosUserAuthProvider'
        db.delete_table('im_astakosuserauthprovider')

        # Deleting model 'Serial'
        db.delete_table('im_serial')

        # Deleting model 'Resource'
        db.delete_table('im_resource')

        # Removing M2M table for field meta on 'Resource'
        db.delete_table('im_resource_meta')

        # Deleting model 'SessionCatalog'
        db.delete_table('im_sessioncatalog')

        # Deleting model 'ProjectMembershipHistory'
        db.delete_table('im_projectmembershiphistory')

        # Deleting model 'AstakosUserQuota'
        db.delete_table('im_astakosuserquota')

        # Deleting model 'ProjectResourceGrant'
        db.delete_table('im_projectresourcegrant')

        # Deleting model 'PendingThirdPartyUser'
        db.delete_table('im_pendingthirdpartyuser')

        # Deleting model 'ProjectApplication'
        db.delete_table('im_projectapplication')

        # Deleting field 'Service.order'
        db.delete_column('im_service', 'order')

        # Deleting field 'AstakosUser.uuid'
        db.delete_column('im_astakosuser', 'uuid')

        # Deleting field 'AstakosUser.disturbed_quota'
        db.delete_column('im_astakosuser', 'disturbed_quota')

        for u in orm.AstakosUser.objects.all():
            u.affiliation = u.affiliation or ''
            u.save()

        # Changing field 'AstakosUser.affiliation'
        db.alter_column('im_astakosuser', 'affiliation', self.gf('django.db.models.fields.CharField')(default='', max_length=255))

        # Changing field 'AstakosUser.provider'
        db.alter_column('im_astakosuser', 'provider', self.gf('django.db.models.fields.CharField')(default='', max_length=255))

        # Adding unique constraint on 'AstakosUser', fields ['third_party_identifier', 'provider']
        db.create_unique('im_astakosuser', ['third_party_identifier', 'provider'])

        # Changin field 'auth_user.username'
        db.alter_column('auth_user', 'username', models.CharField(max_length=30))

Example 118

Project: hortonworks-sandbox Source File: 0001_permissions_and_profiles.py
Function: forwards
    def forwards(self, orm):
        """
        This migration has been customized to support upgrades from Cloudera
        Enterprise 3.5, as well as Hue 1.2
        """
        try:
          # These will be removed if upgrading from a previous version of
          # Cloudera Enterprise
          db.delete_table('userman_groupadministrator')
          db.delete_table('userman_grouprelations')
        except Exception:
         pass
        
        try:
          db.rename_table('userman_userprofile', 'useradmin_userprofile')
          db.delete_column('useradmin_userprofile', 'primary_group_id')
          db.create_index('useradmin_userprofile', ['user_id'])

          db.alter_column('useradmin_userprofile', 'creation_method', models.CharField(editable=True, null=False, max_length=64, default=UserProfile.CreationMethod.HUE))
          for up in UserProfile.objects.all():
            # From when CreationMethod was not an Enum
            # LDAP == 1
            # HUE == 0
            if up.creation_method == '1':
              up.creation_method = UserProfile.CreationMethod.EXTERNAL
            elif up.creation_method == '0':
              up.creation_method = UserProfile.CreationMethod.HUE
            up.save()
        except Exception:
          db.rollback_transaction()  
          db.start_transaction()

          # Adding model 'UserProfile'
          db.create_table('useradmin_userprofile', (
              ('home_directory', self.gf('django.db.models.fields.CharField')(max_length=1024, null=True)),
              ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
              ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], unique=True)),
          ))
          db.commit_transaction()
          db.start_transaction()
          db.send_create_signal('useradmin', ['UserProfile'])

        try:
          db.rename_table('userman_grouppermission', 'useradmin_grouppermission')
          db.rename_column('useradmin_grouppermission', 'desktop_permission_id', 'hue_permission_id')
          db.create_index('useradmin_grouppermission', ['group_id'])
          db.create_index('useradmin_grouppermission', ['hue_permission_id'])
        except Exception:
          db.rollback_transaction()  
          db.start_transaction()

          # Adding model 'GroupPermission'
          db.create_table('useradmin_grouppermission', (
              ('hue_permission', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['useradmin.HuePermission'])),
              ('group', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.Group'])),
              ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
          ))
          db.commit_transaction()
          db.start_transaction()
          db.send_create_signal('useradmin', ['GroupPermission'])

        try:
          db.rename_table('userman_desktoppermission', 'useradmin_huepermission')
        except Exception:
          db.rollback_transaction()  
          db.start_transaction()

          # Adding model 'HuePermission'
          db.create_table('useradmin_huepermission', (
              ('action', self.gf('django.db.models.fields.CharField')(max_length=100)),
              ('app', self.gf('django.db.models.fields.CharField')(max_length=30)),
              ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
              ('description', self.gf('django.db.models.fields.CharField')(max_length=255)),
          ))
          db.commit_transaction()
          db.start_transaction()
          db.send_create_signal('useradmin', ['HuePermission'])

Example 119

Project: philo Source File: entities.py
Function: init
	def __init__(self, field_template=None, **kwargs):
		super(JSONAttribute, self).__init__(**kwargs)
		if field_template is None:
			field_template = models.CharField(max_length=255)
		self.field_template = field_template

Example 120

Project: detective.io Source File: admin.py
Function: formfield_for_dbfield
    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'name':
            # We add temporary choices for this field so
            # it will be threaded as a selectbox
            choices = ( (None, "Will be replaced"), )
            db_field = CharField(
                name=db_field.name,
                verbose_name=db_field.verbose_name,
                primary_key=db_field.primary_key,
                max_length=db_field.max_length,
                blank=db_field.blank,
                rel=db_field.rel,
                default=db_field.default,
                editable=db_field.editable,
                serialize=db_field.serialize,
                unique_for_date=db_field.unique_for_date,
                unique_for_year=db_field.unique_for_year,
                help_text=db_field.help_text,
                db_column=db_field.db_column,
                db_tablespace=db_field.db_tablespace,
                auto_created=db_field.auto_created,
                db_index=db_field.db_index,
                validators=db_field.validators,
                # The ony field we don't copy
                choices=choices
            )

        return super(SearchTermInline, self).formfield_for_dbfield(db_field, **kwargs)

Example 121

Project: django-hvad Source File: models.py
    def create_translations_model(self, model, related_name):
        """ Create the translations model for a shared model.
            model -- the model class to create translations for
            related_name -- the related name for the reverse FK from the translations model.
        """
        model_name = '%sTranslation' % model.__name__
        translation_bases, translation_base_fields = self._scan_model_bases(model)

        attrs = self.fields.copy()
        attrs.update({
            'Meta': self._build_meta_class(
                model, translation_base_fields.union(self.fields).union(('language_code',))
            ),
            '__module__': model.__module__,
        })

        if not model._meta.abstract:
            attrs.update({
                # If this class is abstract, we must not contribute management fields
                'objects': TranslationsModelManager(),
                'language_code': models.CharField(max_length=15, db_index=True),
                # Nullable so we can prevent cascade deletion
                'master': models.ForeignKey(model, related_name=related_name, editable=False,
                                            on_delete=models.CASCADE),
            })

        # Create the new model
        if self.base_class:
            translation_bases.insert(0, self.base_class)
        translations_model = ModelBase(model_name, tuple(translation_bases), attrs)
        translations_model._meta.shared_model = model
        if not model._meta.abstract:
            # Abstract models do not have a DNE class
            bases = (model.DoesNotExist, translations_model.DoesNotExist,)
            translations_model.DoesNotExist = type('DoesNotExist', bases, {})

        # Register it as a global in the shared model's module.
        # This is needed so that Translation model instances, and objects which
        # refer to them, can be properly pickled and unpickled. The Django session
        # and caching frameworks, in particular, depend on this behaviour.
        setattr(sys.modules[model.__module__], model_name, translations_model)
        return translations_model

Example 122

Project: django-hvad Source File: basic.py
    def test_index_together(self):
        class IndexTogetherModel(TranslatableModel):
            sfield_a = models.CharField(max_length=250)
            sfield_b = models.CharField(max_length=250)
            translations = TranslatedFields(
                tfield_a = models.CharField(max_length=250),
                tfield_b = models.CharField(max_length=250),
            )
            class Meta:
                index_together = [('sfield_a', 'sfield_b'), ('tfield_a', 'tfield_b')]

        if django.VERSION >= (1, 7):
            errors = IndexTogetherModel.check()
            self.assertFalse(errors)

        self.assertIn(('sfield_a', 'sfield_b'),
                         IndexTogetherModel._meta.index_together)
        self.assertNotIn(('tfield_a', 'tfield_b'),
                         IndexTogetherModel._meta.index_together)
        self.assertNotIn(('sfield_a', 'sfield_b'),
                      IndexTogetherModel._meta.translations_model._meta.index_together)
        self.assertIn(('tfield_a', 'tfield_b'),
                      IndexTogetherModel._meta.translations_model._meta.index_together)

        with self.assertThrowsWarning(DeprecationWarning):
            class DeprecatedIndexTogetherModel(TranslatableModel):
                translations = TranslatedFields(
                    tfield_a = models.CharField(max_length=250),
                    tfield_b = models.CharField(max_length=250),
                    meta = { 'index_together': [('tfield_a', 'tfield_b')] }
                )
        self.assertIn(('tfield_a', 'tfield_b'),
                      DeprecatedIndexTogetherModel._meta.translations_model._meta.index_together)

        with self.assertRaises(ImproperlyConfigured):
            class InvalidIndexTogetherModel(TranslatableModel):
                sfield = models.CharField(max_length=250)
                translations = TranslatedFields(
                    tfield = models.CharField(max_length=250)
                )
                class Meta:
                    index_together = [('sfield', 'tfield')]

Example 123

Project: galaxy Source File: 0017_changetype_description.py
    def backwards(self, orm):
        for table in ('main_role', 'main_category', 'main_platform', 'main_rolerating', 'main_roleimport', 'main_roleversion'):
            db.alter_column('main_role', 'description', models.CharField(max_length=255, blank=True, default=''))

Example 124

Project: lino Source File: kernel.py
    def kernel_startup(self, site):
        """This is a part of a Lino site startup.  The Django Model
        definitions are done, now Lino analyzes them and does certain
        actions:

        - Verify that there are no more pending injects Install a
          :class:`DisableDeleteHandler
          <lino.core.ddh.DisableDeleteHandler>` for each Model into
          `_lino_ddh`.

        - Install :class:`lino.core.model.Model` attributes and
          methods into Models that don't inherit from it.

        """
        if site.history_aware_logging:
            if len(sys.argv) == 0:
                process_name = 'WSGI'
            else:
                process_name = ' '.join(sys.argv)

            logger.info("Started %s (using %s) --> PID %s",
                        process_name, settings.SETTINGS_MODULE, os.getpid())

            def goodbye():
                logger.info("Done %s (PID %s)", process_name, os.getpid())
            atexit.register(goodbye)

        models_list = get_models(include_auto_created=True)
        # this also triggers django.db.models.loading.cache._populate()

        site.setup_model_spec(site, 'user_model')
        site.setup_model_spec(site, 'project_model')

        for app_name_model, p in list(site.override_modlib_models.items()):
            # app_name_model is the full installed app module name +
            # the model name. It certainly contains at least one dot.
            m = '.'.join(app_name_model.split('.')[-2:])
            resolve_model(
                m,
                strict="%s plugin tries to extend unresolved model '%%s'" %
                p.__class__.__module__)

        for model in models_list:
            #~ print 20130216, model
            #~ fix_field_cache(model)

            # if hasattr(model, '_lino_ddh'):
            if '_lino_ddh' in model.__dict__:
                raise Exception("20150831 %s", model)
            model._lino_ddh = DisableDeleteHandler(model)

            Model.django2lino(model)

            if isinstance(model.hidden_columns, basestring):
                model.hidden_columns = frozenset(
                    fields.fields_list(model, model.hidden_columns))

            if isinstance(model.active_fields, basestring):
                model.active_fields = frozenset(
                    fields.fields_list(model, model.active_fields))

            if isinstance(model.allow_cascaded_delete, basestring):
                model.allow_cascaded_delete = frozenset(
                    fields.fields_list(model, model.allow_cascaded_delete))

            qsf = model.quick_search_fields
            # Attention when inheriting this from from parent model.
            # qsf = model.__dict__.get('quick_search_fields', None)
            if qsf is None:
                fields_list = []
                for field in model._meta.fields:
                    if isinstance(field, models.CharField):
                        fields_list.append(field.name)
                model.quick_search_fields = frozenset(fields_list)
            elif isinstance(qsf, frozenset):
                pass
            elif isinstance(qsf, basestring):
                model.quick_search_fields = frozenset(
                    fields.fields_list(model, model.quick_search_fields))
            else:
                raise ChangedAPI(
                    "{0}.quick_search_fields must be None or a string "
                    "of space-separated field names (not {1})".format(
                        model, qsf))

            qsf = model.quick_search_fields_digit
            if qsf is None:
                fields_list = []
                for field in model._meta.fields:
                    if isinstance(field, (
                            models.IntegerField, models.AutoField)):
                        fields_list.append(field.name)
                model.quick_search_fields_digit = frozenset(fields_list)
            elif isinstance(qsf, frozenset):
                pass
            elif isinstance(qsf, basestring):
                model.quick_search_fields_digit = frozenset(
                    fields.fields_list(model, model.quick_search_fields_digit))
            else:
                raise Exception(
                    "{0}.quick_search_fields_digit must be None or a string "
                    "of space-separated field names (not {1})".format(
                        model, qsf))

            if model._meta.abstract:
                raise Exception("Tiens?")

            # site.modules.define(model._meta.app_label, model.__name__, model)

            for f in model._meta.virtual_fields:
                if isinstance(f, GenericForeignKey):
                    self.GFK_LIST.append(f)

        site.load_actors()

        # vip_classes = (layouts.BaseLayout, fields.Dummy)
        # for a in models.get_apps():
        #     app_label = a.__name__.split('.')[-2]

        #     for k, v in a.__dict__.items():
        #         if isinstance(v, type) and issubclass(v, vip_classes):
        #             site.modules.define(app_label, k, v)

        #         if k.startswith('setup_'):
        #             site.modules.define(app_label, k, v)

        if site.user_types_module:
            import_module(site.user_types_module)
        
        site.setup_choicelists()
        # site.setup_workflows()

        if site.workflows_module:
            import_module(site.workflows_module)

        for model in models_list:
            if model._meta.auto_created:
                continue  # automatic intermediate models created by
                          # ManyToManyField should not disable delete
            # for f, m in model._meta.get_fields_with_model():
            for f in model._meta.get_fields():
                site.install_help_text(f, model, f.name)
                m = f.model

                # Refuse nullable CharFields, but don't trigger on
                # NullableCharField (which is a subclass of CharField).

                if f.__class__ is models.CharField and f.null:
                    msg = "Nullable CharField %s in %s" % (f.name, model)
                    raise Exception(msg)
                elif isinstance(f, models.ForeignKey):
                    if isinstance(f.rel.model, basestring):
                        raise Exception("Could not resolve target %r of "
                                        "ForeignKey '%s' in %s "
                                        "(models are %s)" %
                                        (f.rel.model, f.name, model, models_list))
                    set_default_verbose_name(f)

                    """
                    If JobProvider is an MTI child of Company,
                    then mti.delete_child(JobProvider) must not fail on a
                    JobProvider being referred only by objects that can refer
                    to a Company as well.
                    """
                    if not hasattr(f.rel.model, '_lino_ddh'):
                        msg = "20150824 {1} (needed by {0}) "\
                              "has no _lino_ddh"
                        raise Exception(msg.format(f.rel, f.rel.model))
                    # f.rel.model._lino_ddh.add_fk(f.model, f)
                    # m = f.model._meta.concrete_model
                    # f.rel.model._lino_ddh.add_fk(m, f)
                    f.rel.model._lino_ddh.add_fk(m or model, f)

        self.protect_foreignkeys(models_list)

        for p in site.installed_plugins:
            if isinstance(p, Plugin):
                p.before_analyze()

        # logger.info("20150429 Gonna send pre_analyze signal")
        pre_analyze.send(site, models_list=models_list)
        # logger.info("20150429 pre_analyze signal done")
        # MergeActions are defined in pre_analyze.
        # And MergeAction needs the info in _lino_ddh to correctly find
        # keep_volatiles

        site.setup_actions()

        for model in models_list:

            """Virtual fields declared on the model must have been attached
            before calling Model.site_setup(), e.g. because
            pcsw.Person.site_setup() declares `is_client` as imported
            field.

            """

            model.on_analyze(site)

            for k, v in class_dict_items(model):
                if isinstance(v, fields.VirtualField):
                    v.attach_to_model(model, k)

        #~ logger.info("20130817 attached model vfs")

        actors.discover()

        logger.debug("actors.initialize()")
        for a in actors.actors_list:
            a.class_init()

        dbtables.discover()
        #~ choosers.discover()
        actions.discover_choosers()

        for a in actors.actors_list:
            a.on_analyze(site)

        post_analyze.send(site, models_list=models_list)

        if False:
            logger.info("Languages: %s. %d apps, %d models, %s actors.",
                        ', '.join([li.django_code for li in site.languages]),
                        len(site.modules),
                        len(models_list),
                        len(actors.actors_list))

        #~ logger.info(settings.INSTALLED_APPS)

        site.setup_layouts()

        site.on_each_app('site_setup')  # deprecated

        # Actor.after_site_setup() is called after the apps'
        # site_setup().  Example: pcsw.site_setup() adds a detail to
        # properties.Properties, the base class for
        # properties.PropsByGroup.  The latter would not install a
        # `detail_action` during her after_site_setup() and also would
        # never get it later.

        for a in actors.actors_list:
            a.after_site_setup(site)

        #~ site.on_site_startup()

        site.resolve_virtual_fields()

        self.code_mtime = codetime()
        # We set `code_mtime` only after kernel_startup() because
        # codetime watches only those modules which are already
        # imported.

        self.memo_parser = Parser()

        def url2html(parser, s):
            url_text = s.split(None, 1)
            if len(url_text) == 1:
                url = text = url_text[0]
            else:
                url, text = url_text
            return '<a href="%s" target="_blank">%s</a>' % (url, text)

        self.memo_parser.register_command('url', url2html)

        if site.build_js_cache_on_startup is None:
            site.build_js_cache_on_startup = not (
                settings.DEBUG or is_devserver())

        # web.site_setup(site)

        for a in actors.actors_list:
            
            site.install_help_text(a)
            if a.parameters is not None:
                for name, fld in a.parameters.items():
                    site.install_help_text(fld, a, name)

            for ba in a.get_actions():
                # site.install_help_text(
                #     ba.action.__class__, ba.action.action_name)
                # site.install_help_text(ba.action, a, ba.action.action_name)
                # site.install_help_text(ba.action, ba.action.__class__)
                site.install_help_text(ba.action.__class__)
            
            if a.get_welcome_messages is not None:
                site.add_welcome_handler(a.get_welcome_messages)
            if a.welcome_message_when_count is not None:
                
                cls = a
                
                def get_welcome_messages(ar):
                    sar = ar.spawn(cls)
                    # if not cls.get_view_permission(ar.get_user().profile):
                    if not sar.get_permission():
                        # raise Exception(20160814)
                        return
                    num = sar.get_total_count()
                    if num > cls.welcome_message_when_count:
                        chunks = [six.text_type(_("You have "))]
                        txt = _("{0} items in {1}").format(num, cls.label)
                        chunks.append(ar.href_to_request(sar, txt))
                        chunks.append('.')
                        yield E.span(*chunks)                
               
                site.add_welcome_handler(get_welcome_messages)

        pre_ui_build.send(self)

        self.reserved_names = [getattr(constants, n)
                               for n in constants.URL_PARAMS]

        names = set()
        for n in self.reserved_names:
            if n in names:
                raise Exception("Duplicate reserved name %r" % n)
            names.add(n)

        # 20160530
        # self.html_renderer = HtmlRenderer(self)
        # self.text_renderer = TextRenderer(self)

        for p in site.installed_plugins:
            p.on_ui_init(self)

        ui = None
        if self.site.default_ui is None:
            for p in self.site.installed_plugins:
                if p.ui_handle_attr_name is not None:
                    ui = p
                    break
            # if ui is None:
            #     raise Exception("No user interface in {0}".format(
            #         [u.app_name for u in self.site.installed_plugins]))

        else:
            for p in self.site.installed_plugins:
                if p.app_name == self.site.default_ui:
                    ui = p
            if ui is None:
                raise Exception(
                    "Invalid value %r for `default_ui` "
                    "(must be None or the name of an installed plugin)"
                    % self.site.default_ui)
            ui.url_prefix = None

        if ui is not None:
            self.default_renderer = ui.renderer
            self.default_ui = ui

        # 20160530
        self.html_renderer = HtmlRenderer(ui)
        self.text_renderer = TextRenderer(ui)

        post_ui_build.send(self)

        if ui is not None:

            # trigger creation of params_layout.params_store
            for res in actors.actors_list:
                for ba in res.get_actions():
                    if ba.action.params_layout is not None:
                        ba.action.params_layout.get_layout_handle(
                            self.default_ui)

Example 125

Project: lino Source File: model.py
    @classmethod
    def lookup_or_create(model, lookup_field, value, **known_values):
        """
        Look-up whether there is a model instance having
        `lookup_field` with value `value`
        (and optionally other `known_values` matching exactly).
        
        If it doesn't exist, create it and emit an
        :attr:`auto_create <lino.core.signals.auto_create>` signal.
        
        """

        from lino.utils.mldbc.fields import BabelCharField

        #~ logger.info("2013011 lookup_or_create")
        fkw = dict()
        fkw.update(known_values)

        if isinstance(lookup_field, basestring):
            lookup_field = model._meta.get_field(lookup_field)
        if isinstance(lookup_field, BabelCharField):
            flt = settings.SITE.lookup_filter(
                lookup_field.name, value, **known_values)
        else:
            if isinstance(lookup_field, models.CharField):
                fkw[lookup_field.name + '__iexact'] = value
            else:
                fkw[lookup_field.name] = value
            flt = models.Q(**fkw)
            #~ flt = models.Q(**{self.lookup_field.name: value})
        qs = model.objects.filter(flt)
        if qs.count() > 0:  # if there are multiple objects, return the first
            if qs.count() > 1:
                logger.warning(
                    "%d %s instances having %s=%r (I'll return the first).",
                    qs.count(), model.__name__, lookup_field.name, value)
            return qs[0]
        #~ known_values[lookup_field.name] = value
        obj = model(**known_values)
        setattr(obj, lookup_field.name, value)
        try:
            obj.full_clean()
        except ValidationError as e:
            raise ValidationError("Failed to auto_create %s : %s" %
                                  (obj2str(obj), e))
        obj.save()
        signals.auto_create.send(obj, known_values=known_values)
        return obj

Example 126

Project: djorm-ext-pgfulltext Source File: models.py
    def _find_text_fields(self):
        fields = [f for f in self.model._meta.fields
                  if isinstance(f, (models.CharField, models.TextField))]

        return [(f.name, None) for f in fields]

Example 127

Project: localwiki-backend-server Source File: models.py
    def get_extra_history_fields(self, model):
        """
        Extra, non-essential fields for the historical models.

        If you subclass ChangesTracker this is a good method to over-ride:
        simply add your own values to the fields for custom fields.

        NOTE: Your custom fields should start with history_ if you want them
              to be looked up via hm.version_info.fieldname

        Here's an example of extending to add a descriptive textfield::

            def get_extra_history_fields(self, model):
                # Keep base_attrs -- we like user tracking!
                attrs = super(MyTrackChanges, self).get_extra_history_fields()
                attrs['history_long_description'] = models.TextField(
                    blank=True, null=True)
                return attrs

        Returns:
            A dictionary of fields that will be added to the historical
            record model.
        """
        def _history_user_link(m):
            if m.version_info.user:
                user = m.version_info.user
                return '<a href="%s">%s</a>' % (user.get_absolute_url(), user)
            else:
                if getattr(settings, 'SHOW_IP_ADDRESSES', True):
                    return m.version_info.user_ip
                else:
                    return 'unknown'
        attrs = {
            'history_comment': models.CharField(max_length=200, blank=True,
                null=True),
            'history_user': fields.AutoUserField(null=True),
            'history_user_ip': fields.AutoIPAddressField(null=True),
            'history_user_link': _history_user_link,
            '__unicode__': lambda self: u'%s as of %s' % (
                self.history__object, self.history_date),
        }
        return attrs

Example 128

Project: make.mozilla.org Source File: db.py
Function: test_sql_defaults
    def test_sql_defaults(self):
        """
        Test that sql default value is correct for non-string field types.
        """
        from datetime import datetime

        class CustomField(models.CharField):
            __metaclass__ = models.SubfieldBase
            description = 'CustomField'
            def get_default(self):
                if self.has_default():
                    if callable(self.default):
                        return self.default()
                    return self.default
                return super(CustomField, self).get_default()
            def get_prep_value(self, value):
                if not value:
                    return value
                return ','.join(map(str, value))
            def to_python(self, value):
                if not value or isinstance(value, list):
                    return value
                return map(int, value.split(','))

        false_value = db.has_booleans and 'False' or '0' 
        defaults = (
            #(models.DateTimeField(default=datetime(2012, 12, 21, 0, 0, 1)), 'DEFAULT \'2012-12-21 00:00:01'), # replaced by test_datetime_default
            (models.CharField(default='sukasuka'), 'DEFAULT \'sukasuka'),
            (models.BooleanField(default=False), 'DEFAULT %s' % false_value),
            (models.IntegerField(default=42), 'DEFAULT 42'),
            (CustomField(default=[2012,2018,2021,2036]), 'DEFAULT \'2012,2018,2021,2036')
        )
        for field, sql_test_str in defaults:
            sql = db.column_sql('fish', 'YAAAAAAZ', field)
            if sql_test_str not in sql:
                self.fail("default sql value was not properly generated for field %r.\nSql was %s" % (field,sql))   

Example 129

Project: zamboni Source File: models.py
Function: address_fields
    @classmethod
    def address_fields(cls):
        return [field.name for field in cls._meta.fields
                if isinstance(field, (models.CharField, models.EmailField))]

Example 130

Project: nnmware Source File: fields.py
def std_text_field(verbose, max_length=255):
    return models.CharField(verbose_name=verbose, max_length=max_length, blank=True, default='')

Example 131

Project: django-multilingual-ng Source File: translation.py
    def finish_multilingual_class(cls, *args, **kwargs):
        """
        Create a model with translations of a multilingual class.
        """

        main_cls = kwargs['sender']
        translation_model_name = main_cls.__name__ + "Translation"

        # create the model with all the translatable fields
        unique = [('language_code', 'master')]
        for f in cls.get_unique_fields():
            unique.append(('language_code',f))

        class TransMeta:
            pass

        try:
            meta = cls.Meta
        except AttributeError:
            meta = TransMeta

        meta.ordering = ('language_code',)
        meta.unique_together = tuple(unique)
        meta.app_label = main_cls._meta.app_label
        if not hasattr(meta, 'db_table'):
            meta.db_table = main_cls._meta.db_table + '_translation'

        trans_attrs = cls.__dict__.copy()
        trans_attrs['Meta'] = meta
        # TODO: increase the length of this field, but to what???
        trans_attrs['language_code'] = models.CharField(max_length=15, blank=True,
                                                        choices=get_language_choices(),
                                                        db_index=True)
        
        related_name = getattr(meta, 'related_name', 'translations')
        if hasattr(meta, 'related_name'):
            delattr(meta, 'related_name')
        
        edit_inline = True

        trans_attrs['master'] = TranslationForeignKey(main_cls, blank=False, null=False,
                                                      related_name=related_name,)
        trans_attrs['__str__'] = lambda self: ("%s object, language_code=%s"
                                               % (translation_model_name,
                                                  self.language_code))

        trans_model = ModelBase(translation_model_name, (models.Model,), trans_attrs)
        trans_model._meta.translated_fields = cls.create_translation_attrs(main_cls)
        trans_model._meta.related_name = related_name

        _old_init_name_map = main_cls._meta.__class__.init_name_map
        def init_name_map(self):
            cache = _old_init_name_map(self)
            for name, field_and_lang_id in trans_model._meta.translated_fields.items():
                #import sys; sys.stderr.write('TM %r\n' % trans_model)
                cache[name] = (field_and_lang_id[0], trans_model, True, False)
            return cache
        main_cls._meta.init_name_map = instancemethod(init_name_map,
                                                      main_cls._meta,
                                                      main_cls._meta.__class__)

        main_cls._meta.translation_model = trans_model
        main_cls._meta.force_language = None
        main_cls.Translation = trans_model
        main_cls.get_translation = get_translation
        main_cls.fill_translation_cache = fill_translation_cache

Example 132

Project: gro-api Source File: models.py
def generate_model_from_entity(entity):
    def to_string(self):
        return self.name
    model_attrs = {
        '__module__': __name__,
        'model_name': entity.name,
        'name': models.CharField(max_length=100, blank=True),
        'x': models.FloatField(default=0),
        'y': models.FloatField(default=0),
        'z': models.FloatField(default=0),
        'length': models.FloatField(default=0),
        'width': models.FloatField(default=0),
        'height': models.FloatField(default=0),
        'model': models.ForeignKey(Model3D, null=True, related_name='+'),
        'parent': ParentField(entity.name),
        'resources': GenericRelation(
            Resource, object_id_field='location_id',
            content_type_field='location_type'
        ),
        '__str__': to_string,
        '__doc__': entity.description
    }
    return type(entity.name, (models.Model,), model_attrs)

Example 133

Project: oh-mainline Source File: 0011_permit_nulls_in_last_touched_and_rename_tag_type.py
Function: backwards
    def backwards(self, orm):
        
        # Deleting field 'ProjectExp.time_start'
        db.delete_column('profile_projectexp', 'time_start')
        
        # Deleting field 'ProjectExp.last_touched'
        db.delete_column('profile_projectexp', 'last_touched')
        
        # Deleting field 'Tag.tag_type'
        db.delete_column('profile_tag', 'tag_type_id')
        
        # Deleting field 'ProjectExp.time_finish'
        db.delete_column('profile_projectexp', 'time_finish')
        
        # Adding field 'Tag.type'
        db.add_column('profile_tag', 'type', models.CharField(max_length=50))
        
        # Adding field 'ProjectExp.tags'
        db.add_column('profile_projectexp', 'tags', models.TextField())
        
        # 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, 50, 22, 475279)))
        
        # Changing field 'Person.last_touched'
        db.alter_column('profile_person', 'last_touched', models.DateTimeField())
        
        # 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, 50, 22, 339421)))
        
        # Changing field 'ProjectExp.url'
        db.alter_column('profile_projectexp', 'url', models.URLField(max_length=200))
        
        # Changing field 'ProjectExp.man_months'
        db.alter_column('profile_projectexp', 'man_months', models.PositiveIntegerField())
        
        # Changing field 'ProjectExp.source'
        db.alter_column('profile_projectexp', 'source', models.CharField(max_length=100))
        
        # Changing field 'ProjectExp.primary_language'
        db.alter_column('profile_projectexp', 'primary_language', models.CharField(max_length=200))
        
        # Changing field 'ProjectExp.time_record_was_created'
        db.alter_column('profile_projectexp', 'time_record_was_created', models.DateTimeField())

Example 134

Project: oh-mainline Source File: 0002_milestone_b_data.py
Function: forwards
    def forwards(self, orm):
        
        try:
            # Adding field 'Bug.submitter_realname'
            db.add_column('search_bug', 'submitter_realname', models.CharField(max_length=200))
        except:
            pass

        try:
             # Adding field 'Project.icon_url'
            db.add_column('search_project', 'icon_url', models.URLField(max_length=200))
        except:
            pass
        
        try:
            # Adding field 'Bug.last_touched'
            db.add_column('search_bug', 'last_touched', models.DateField(default=datetime.datetime(1970, 1, 1, 12, 0, 0)))
        except:
            pass
        
        try:
            # Adding field 'Bug.importance'
            db.add_column('search_bug', 'importance', models.CharField(max_length=200))
        except:
            pass
        
        try:
            # Adding field 'Bug.people_involved'
            db.add_column('search_bug', 'people_involved', models.IntegerField(default=0))
        except:
            pass
        
        try:
            # Adding field 'Bug.last_polled'
            db.add_column('search_bug', 'last_polled', models.DateField(default=datetime.datetime(1970, 1, 1, 12, 0, 0)))
        except:
            pass
        
        try:
            # Adding field 'Bug.submitter_username'
            db.add_column('search_bug', 'submitter_username', models.CharField(max_length=200))
        except:
            pass

Example 135

Project: fuel-devops Source File: base.py
Function: choices
def choices(*args, **kwargs):
    defaults = {'max_length': 255, 'null': False}
    defaults.update(kwargs)
    defaults.update(choices=list(zip(args, args)))
    return models.CharField(**defaults)
See More Examples - Go to Next Page
Page 1 Page 2 Page 3 Selected