Python django.db.models.CharField() Examples

The following are 30 code examples of django.db.models.CharField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models , or try the search function .
Example #1
Source File: views.py    From timed-backend with GNU Affero General Public License v3.0 9 votes vote down vote up
def get_queryset(self):
        date = self._extract_date()
        user = self.request.user
        queryset = get_user_model().objects.values("id")
        queryset = queryset.annotate(date=Value(date, DateField()))
        # last_reported_date filter is set, a date can only be calucated
        # for users with either at least one absence or report
        if date is None:
            users_with_reports = Report.objects.values("user").distinct()
            users_with_absences = Absence.objects.values("user").distinct()
            active_users = users_with_reports.union(users_with_absences)
            queryset = queryset.filter(id__in=active_users)

        queryset = queryset.annotate(
            pk=Concat("id", Value("_"), "date", output_field=CharField())
        )

        if not user.is_superuser:
            queryset = queryset.filter(Q(id=user.id) | Q(supervisors=user))

        return queryset 
Example #2
Source File: views.py    From timed-backend with GNU Affero General Public License v3.0 8 votes vote down vote up
def get_queryset(self):
        date = self._extract_date()
        user = self._extract_user()

        queryset = models.AbsenceType.objects.values("id")
        queryset = queryset.annotate(date=Value(date, DateField()))
        queryset = queryset.annotate(user=Value(user.id, IntegerField()))
        queryset = queryset.annotate(
            pk=Concat(
                "user", Value("_"), "id", Value("_"), "date", output_field=CharField()
            )
        )

        # only myself, superuser and supervisors may see by absence balances
        current_user = self.request.user

        if not current_user.is_superuser:
            if current_user.id != user.id:
                if not current_user.supervisees.filter(id=user.id).exists():
                    return models.AbsenceType.objects.none()

        return queryset 
Example #3
Source File: 0002_pk_migration.py    From django-rest-passwordreset with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def get_migrations_for_django_21_and_newer():
    return [
        # remove primary key information from 'key' field
        migrations.AlterField(
            model_name='resetpasswordtoken',
            name='key',
            field=models.CharField(db_index=True, primary_key=False, max_length=64, unique=True, verbose_name='Key'),
        ),
        # add a new id field
        migrations.AddField(
            model_name='resetpasswordtoken',
            name='id',
            field=models.AutoField(primary_key=True, serialize=False),
            preserve_default=False,
        ),
        migrations.RunPython(
            populate_auto_incrementing_pk_field,
            migrations.RunPython.noop
        ),
    ] 
Example #4
Source File: registration.py    From byro with Apache License 2.0 6 votes vote down vote up
def build_default_field(self, field, model):
        choices = getattr(field, "choices", None)
        if choices:
            return forms.ChoiceField(
                required=False,
                label=_("Default value"),
                choices=[(None, "-----------")] + list(choices),
            )
        if not (model is Member and field.name == "number"):
            if isinstance(field, models.CharField):
                return forms.CharField(required=False, label=_("Default value"))
            elif isinstance(field, models.DecimalField):
                return forms.DecimalField(
                    required=False,
                    label=_("Default value"),
                    max_digits=field.max_digits,
                    decimal_places=field.decimal_places,
                )
            elif isinstance(field, models.DateField):
                return forms.CharField(required=False, label=_("Other/fixed date")) 
Example #5
Source File: test_docstrings.py    From sphinxcontrib-django with Apache License 2.0 6 votes vote down vote up
def test_model_init_params(self):
        """Model __init__ gets all fields as params."""
        lines = []
        docstrings._add_model_fields_as_params(self.app, SimpleModel, lines)
        self.assertEqual(
            lines,
            [
                ":param id: Id",
                ":type id: AutoField",
                ":param user: User",
                ":type user: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param user2: User2",
                ":type user2: ForeignKey to"
                " :class:`~sphinxcontrib_django.tests.test_docstrings.User2`",
                ":param user3: User3",
                ":type user3: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param dummy_field: Dummy field",
                ":type dummy_field: CharField",
            ],
        ) 
Example #6
Source File: test_docstrings.py    From sphinxcontrib-django with Apache License 2.0 6 votes vote down vote up
def test_add_form_fields(self):
        """Form fields should be mentioned."""
        lines = []
        docstrings._add_form_fields(SimpleForm, lines)
        self.assertEqual(
            lines,
            [
                "**Form fields:**",
                "",
                "* ``user``: User (:class:`~django.forms.models.ModelChoiceField`)",
                "* ``user2``: User2 (:class:`~django.forms.models.ModelChoiceField`)",
                "* ``user3``: User3 (:class:`~django.forms.models.ModelChoiceField`)",
                "* ``test1``: Test1 (:class:`~django.forms.fields.CharField`)",
                "* ``test2``: Test2 (:class:`~django.forms.fields.CharField`)",
            ],
        ) 
Example #7
Source File: admin.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def owner_search_fields(self):
        """
        Returns all the fields that are CharFields except for password from the
        User model.  For the built-in User model, that means username,
        first_name, last_name, and email.
        """
        try:
            from django.contrib.auth import get_user_model
        except ImportError:  # Django < 1.5
            from django.contrib.auth.models import User
        else:
            User = get_user_model()
        return [
            field.name for field in User._meta.fields
            if isinstance(field, models.CharField) and field.name != 'password'
        ] 
Example #8
Source File: test_expressions.py    From django-localized-fields with MIT License 6 votes vote down vote up
def setUpClass(cls):
        """Creates the test model in the database."""

        super(LocalizedExpressionsTestCase, cls).setUpClass()

        cls.TestModel1 = get_fake_model(
            {"name": models.CharField(null=False, blank=False, max_length=255)}
        )

        cls.TestModel2 = get_fake_model(
            {
                "text": LocalizedField(),
                "other": models.ForeignKey(
                    cls.TestModel1,
                    related_name="features",
                    on_delete=models.CASCADE,
                ),
            }
        ) 
Example #9
Source File: test_slug_fields.py    From django-localized-fields with MIT License 6 votes vote down vote up
def test_populate_multiple_from_fields():
        """Tests whether populating the slug from multiple fields works
        correctly."""

        model = get_fake_model(
            {
                "title": LocalizedField(),
                "name": models.CharField(max_length=255),
                "slug": LocalizedUniqueSlugField(
                    populate_from=("title", "name")
                ),
            }
        )

        obj = model()
        for lang_code, lang_name in settings.LANGUAGES:
            obj.name = "swen"
            obj.title.set(lang_code, "title %s" % lang_name)

        obj.save()

        for lang_code, lang_name in settings.LANGUAGES:
            assert (
                obj.slug.get(lang_code) == "title-%s-swen" % lang_name.lower()
            ) 
Example #10
Source File: utils.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def allow_search_fields(cls, exclude=None):
    opts = cls._meta
    if not exclude:
        exclude = ['onidc', 'slug', 'created', 'modified']
    exclude.extend([f.name for f in opts.fields if getattr(f, 'choices')])
    fields = []
    for f in opts.fields:
        if exclude and f.name in exclude:
            continue
        if isinstance(f, models.ForeignKey):
            submodel = f.related_model
            for sub in submodel._meta.fields:
                if exclude and sub.name in exclude:
                    continue
                if isinstance(sub, models.CharField) \
                        and not getattr(sub, 'choices'):
                    fields.append(f.name + '__' + sub.name + '__icontains')
        if isinstance(f, models.CharField):
            fields.append(f.name + '__icontains')
    return fields 
Example #11
Source File: models.py    From django-ra-erp with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_redirect_url_prefix(cls):
        """
        Get the url for the change list of this model
        :return: a string url
        """
        return reverse('%s:%s_%s_changelist' % (
            app_settings.RA_ADMIN_SITE_NAME, cls._meta.app_label, cls.get_class_name().lower()))


# class BasePersonInfo(BaseInfo):
#     address = models.CharField(_('address'), max_length=260, null=True, blank=True)
#     telephone = models.CharField(_('telephone'), max_length=130, null=True, blank=True)
#     email = models.EmailField(_('email'), null=True, blank=True)
#
#     class Meta:
#         abstract = True
#         # swappable = swapper.swappable_setting('ra', 'BasePersonInfo') 
Example #12
Source File: effort.py    From richie with MIT License 5 votes vote down vote up
def value_to_string(self, obj):
        """Serialize the Python value. We can use existing methods as it is a CharField."""
        value = self.value_from_object(obj)
        return self.get_prep_value(value) 
Example #13
Source File: histogram.py    From django-pivot with MIT License 5 votes vote down vote up
def simple_histogram(queryset, column, bins):
    """
    Return a histogram from data in queryset.

    :param queryset: A Queryet, Model, or Manager
    :param column: The column we are aggregating into a histogram
    :param bins: An ordered iterable of left endpoints of the bins. Must have at least two elements.
    The endpoints must be a convertible to strings by force_text
    :return: A dictionary with bin endpoints converted to strings as keys and
    """
    queryset = _get_queryset(queryset)

    queryset = queryset.annotate(column_name=Value(column, output_field=CharField()))

    return multi_histogram(queryset, column, bins, slice_on='column_name', choices=((column, column),)) 
Example #14
Source File: test_form.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def test_template_name(self):
        field = self.get_field(Form, "template_name")
        self.assertModelField(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertEqual(field.choices, get_setting("FORM_TEMPLATES")) 
Example #15
Source File: test_form.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def test_submit_button_text(self):
        field = self.get_field(Form, "submit_button_text")
        self.assertModelField(field, models.CharField, False, False, "Submit")
        self.assertEqual(field.max_length, 100) 
Example #16
Source File: test_form.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def test_success_message(self):
        field = self.get_field(Form, "success_message")
        self.assertModelField(field, models.CharField, False, True)
        self.assertEqual(field.max_length, 255) 
Example #17
Source File: test_form.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def test_error_message(self):
        field = self.get_field(Form, "error_message")
        self.assertModelField(field, models.CharField, False, True)
        self.assertEqual(field.max_length, 255) 
Example #18
Source File: test.py    From django-pivot with MIT License 5 votes vote down vote up
def __init__(self, *expressions, **extra):
        strf = extra.pop('format', None)
        extra['format'] = strf.replace("%", "%%")
        extra['output_field'] = CharField()
        super(DateFormat, self).__init__(*expressions, **extra) 
Example #19
Source File: views.py    From rdmo with Apache License 2.0 5 votes vote down vote up
def get_queryset(self):
        # prepare When statements for conditional expression
        case_args = []
        for role, text in Membership.ROLE_CHOICES:
            case_args.append(models.When(membership__role=role, then=models.Value(str(text))))

        return Project.objects.filter(user=self.request.user).annotate(role=models.Case(
            *case_args,
            default=None,
            output_field=models.CharField()
        )) 
Example #20
Source File: test_slug_fields.py    From django-localized-fields with MIT License 5 votes vote down vote up
def setUpClass(cls):
        """Creates the test models in the database."""

        super(LocalizedSlugFieldTestCase, cls).setUpClass()

        cls.Model = get_fake_model(
            {
                "title": LocalizedField(),
                "name": models.CharField(max_length=255),
                "slug": LocalizedUniqueSlugField(populate_from="title"),
            }
        ) 
Example #21
Source File: models.py    From patchew with MIT License 5 votes vote down vote up
def HeaderFieldModel(**args):
    return models.CharField(max_length=4096, **args) 
Example #22
Source File: filters.py    From CTF_AWD_Platform with MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example #23
Source File: filters.py    From myblog with GNU Affero General Public License v3.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example #24
Source File: problem.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_problem_i18n_name(self, key, language, name_field=None):
        queryset = self._clone() if name_field is None else self.annotate(_name=F(name_field))
        alias = unique_together_left_join(queryset, ProblemTranslation, 'problem', 'language', language,
                                          parent_model=Problem)
        # You must specify name_field if Problem is not yet joined into the QuerySet.
        kwargs = {key: Coalesce(RawSQL('%s.name' % alias, ()),
                                F(name_field) if name_field else RawSQLColumn(Problem, 'name'),
                                output_field=models.CharField())}
        return queryset.annotate(**kwargs) 
Example #25
Source File: models.py    From django-carrot with Apache License 2.0 5 votes vote down vote up
def __str__(self) -> models.CharField:
        return self.task 
Example #26
Source File: models.py    From django-carrot with Apache License 2.0 5 votes vote down vote up
def __str__(self) -> models.CharField:
        return self.task 
Example #27
Source File: models.py    From imooc with Apache License 2.0 5 votes vote down vote up
def __init__(self, expression, distinct=False, ordering=None, separator=',', **extra):
        super(GroupConcat, self).__init__(expression,
                                          distinct='DISTINCT ' if distinct else '',
                                          ordering=' ORDER BY %s' % ordering if ordering is not None else '',
                                          separator=' SEPARATOR "%s"' % separator,
                                          output_field=models.CharField(), **extra) 
Example #28
Source File: functions.py    From django-rdkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, expression):
        super(FMCS, self).__init__(expression, output_field=models.CharField()) 
Example #29
Source File: models.py    From gro-api with GNU General Public License v2.0 5 votes vote down vote up
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)

# A dictionary of all of the classes in the layout tree that have been created
# so we can be sure not to create a class that has already been created 
Example #30
Source File: fields.py    From prospector with GNU General Public License v3.0 5 votes vote down vote up
def formfield(self, form_class=forms.CharField, **kwargs):
        kwargs['widget'] = forms.PasswordInput

        return super().formfield(form_class=form_class, **kwargs)