Python django.db.models.CharField() Examples

The following are code examples for showing how to use django.db.models.CharField(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: djangoshop-shopit   Author: dinoperovic   File: categorization.py    (license) View Source Project 7 votes vote down vote up
def _categorization_translated_fields():
    return TranslatedFields(
        name=models.CharField(
            _('Name'),
            max_length=128,
        ),
        slug=models.SlugField(
            _('Slug'),
            db_index=True,
        ),
        description=models.TextField(
            _('Description'),
            blank=True,
            help_text=_("Description of a categorization, usually used as lead text in categorization's detail view."),
        ),
        meta={
            'unique_together': [('language_code', 'slug')],
        },
    ) 
Example 2
Project: linkedin_recommend   Author: duggalr2   File: models.py    (license) View Source Project 6 votes vote down vote up
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()


# class ParsedProfile(models.Model):
#     user = models.OneToOneField(User, on_delete=models.CASCADE)
#     name = models.CharField(max_length=250)
#     header = models.CharField(max_length=500, null=True)
#     url = models.CharField(max_length=500)
#     school = models.CharField(max_length=500, null=True)
#     school_program = models.CharField(max_length=500, null=True)
#
#
# class JobTitle(models.Model):
#     profile = models.ForeignKey(ParsedProfile, on_delete=models.CASCADE)
#     job = models.CharField(max_length=500, null=True)
#
#
# class Location(models.Model):
#     profile = models.ForeignKey(ParsedProfile, on_delete=models.CASCADE)
#     loc = models.CharField(max_length=500, default=None)


# Below is All The Profiles that were originally in DB and added new ones by User
# Initial Profiles, only 2000 were in DB (mainly SE/CS focused) 
Example 3
Project: ecs_sclm   Author: meaningful   File: folderadmin.py    (license) View Source Project 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 4
Project: django-modeltrans   Author: zostera   File: test_translating.py    (license) View Source Project 6 votes vote down vote up
def test_get_i18n_field(self):
        self.assertEquals(get_i18n_field(app_models.Blog), app_models.Blog._meta.get_field('i18n'))

        class I18nFieldTestModel(models.Model):
            test = models.CharField(max_length=20)

            class Meta:
                app_label = 'django-modeltrans_tests'

        self.assertEquals(get_i18n_field(I18nFieldTestModel), None)

        class I18nFieldTestModel2(models.Model):
            test = models.CharField(max_length=20)
            i18n = models.CharField(max_length=20)

            class Meta:
                app_label = 'django-modeltrans_tests'

        self.assertEquals(get_i18n_field(I18nFieldTestModel2), None) 
Example 5
Project: django-modeltrans   Author: zostera   File: test_translating.py    (license) View Source Project 6 votes vote down vote up
def test_translate_model_with_existing_field(self):
        class TestModel2(models.Model):
            title = models.CharField(max_length=100)
            title_nl = models.CharField(max_length=100)

            i18n = TranslationField(fields=('title', ))

            class Meta:
                app_label = 'django-modeltrans_tests'

        expected_message = (
            'Error adding translation field. Model "TestModel2" already '
            'contains a field named "title_nl".'
        )

        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
            translate_model(TestModel2) 
Example 6
Project: django-modeltrans   Author: zostera   File: test_translating.py    (license) View Source Project 6 votes vote down vote up
def test_model_meta_ordering_pk(self):
        '''
        When Model.Meta.ordering contains 'pk'
        '''

        class OrderByPkModel(models.Model):
            title = models.CharField(max_length=100)

            i18n = TranslationField(fields=('title', ))

            class Meta:
                app_label = 'django-modeltrans_tests'
                ordering = ('-pk', )

        translate_model(OrderByPkModel)
        sql = str(OrderByPkModel.objects.all().query)

        self.assertIn('ORDER BY "django-modeltrans_tests_orderbypkmodel"."id" DESC', sql) 
Example 7
Project: mp-novaposhta   Author: pmaigutyak   File: 0002_model_translation.py    (license) View Source Project 6 votes vote down vote up
def generate_operations():

    operations = []

    for code, name in settings.LANGUAGES:

        operations += [

            migrations.AddField(
                model_name='warehouse',
                name='address_%s' % code,
                field=models.CharField(db_index=True, max_length=255, null=True, verbose_name='Address'),
            ),
            migrations.AddField(
                model_name='warehouse',
                name='title_%s' % code,
                field=models.CharField(db_index=True, max_length=255, null=True, verbose_name='Title'),
            ),

        ]

        return operations 
Example 8
Project: mentoringtool   Author: cindycaobutler   File: program.py    (license) View Source Project 6 votes vote down vote up
def mantaince(self):
		if datetime.date.today() - self.updated_at.days > 30:
			self.prog_stats["no_of_users_this_month"] = 0



# class ProgStat(models.Model):
# 	'''
# 	no_of_users: integer
# 	no_of_users_this_month: integer
# 	'''

# 	no_of_users = models.IntegerField(default='0')
# 	no_of_users_this_month = models.IntegerField(default='0')

# class Mentors(models.Model):
# 	'''
# 	Mentor name and id
# 	'''

# 	name = models.CharField(max_length=64)
# 	mid = models.IntegerField(default='0') 
Example 9
Project: prngmgr   Author: wolcomm   File: models.py    (license) View Source Project 6 votes vote down vote up
def status_summary(self):
        """Get interface status summary."""
        base_query_set = super(PeeringSessionManager, self).get_queryset()
        summary = base_query_set.annotate(
            label=models.Case(
                models.When(provisioning_state=2, then=models.Case(
                    models.When(admin_state=2, then=models.Case(
                        models.When(operational_state=6,
                                    then=models.Value('Up')),
                        default=models.Value('Down')
                    )),
                    default=models.Value('Admin Down')
                )),
                models.When(provisioning_state=1,
                            then=models.Value('Provisioning')),
                default=models.Value('None'),
                output_field=models.CharField()
            )).values('label').annotate(value=models.Count('label'))
        return summary 
Example 10
Project: pretalx   Author: pretalx   File: views.py    (license) View Source Project 6 votes vote down vote up
def sort_queryset(self, qs):
        sort_key = self.request.GET.get('sort')
        if sort_key:
            plain_key = sort_key[1:] if sort_key.startswith('-') else sort_key
            reverse = not (plain_key == sort_key)
            if plain_key in self.sortable_fields:
                is_text = False
                with suppress(FieldDoesNotExist):
                    is_text = isinstance(qs.model._meta.get_field(plain_key), CharField)

                if is_text:
                    # TODO: this only sorts direct lookups case insensitively
                    # A sorting field like 'speaker__name' will not be found
                    qs = qs.annotate(key=Lower(plain_key)).order_by('-key' if reverse else 'key')
                else:
                    qs = qs.order_by(sort_key)
        return qs 
Example 11
Project: Django-Web-Development-with-Python   Author: PacktPublishing   File: views.py    (license) View Source Project 6 votes vote down vote up
def viral_video_detail(request, id):
    yesterday = datetime.date.today() - datetime.timedelta(days=1)

    qs = ViralVideo.objects.annotate(
        total_impressions=models.F("desktop_impressions") + models.F("mobile_impressions"),
        label=models.Case(
            models.When(total_impressions__gt=POPULAR_FROM, then=models.Value("popular")),
            models.When(created__gt=yesterday, then=models.Value("new")),
            default=models.Value("cool"),
            output_field=models.CharField(),
        ),
    )

    # DEBUG: check the SQL query that Django ORM generates
    print(qs.query)

    qs = qs.filter(pk=id)
    if request.flavour == "mobile":
        qs.update(mobile_impressions=models.F("mobile_impressions") + 1)
    else:
        qs.update(desktop_impressions=models.F("desktop_impressions") + 1)

    video = get_object_or_404(qs)

    return render(request, "viral_videos/viral_video_detail.html", {'video': video}) 
Example 12
Project: team-budget   Author: hackoregon   File: views.py    (license) View Source Project 6 votes vote down vote up
def get_queryset(self):
        """
        Append the calculated service area based on business logic.
        (Some bureaus are in service areas not reflected by the data)
        """
        qs = models.BudgetHistory.objects.all()
        qs = qs.values('fiscal_year', 'service_area_code', 'bureau_code', 'bureau_name').annotate(
            sa_calced=Case(
                When(bureau_code__in = LA_Bureaus, then = Value('LA')),
                When(bureau_code__in = EO_Bureaus, then = Value('EO')),
                default = 'service_area_code',
                output_field = CharField()
            ),
            amount=Sum('amount'))
        qs = qs.order_by('fiscal_year', 'service_area_code', 'bureau_code', 'bureau_name')
        return qs 
Example 13
Project: team-budget   Author: hackoregon   File: views.py    (license) View Source Project 6 votes vote down vote up
def get_queryset(self):
        """
        Calculate service area based on business logic.
        (Some bureaus are in service areas not reflected by the data)
        """
        qs = models.BudgetHistory.objects.all()
        qs = qs.values('fiscal_year', ).annotate(
            sa_calced=Case(
                When(bureau_code__in = LA_Bureaus, then = Value('LA')),
                When(bureau_code__in = EO_Bureaus, then = Value('EO')),
                default = 'service_area_code',
                output_field = CharField()
            ),
            amount=Sum('amount'),
        )
        qs = qs.order_by('fiscal_year', 'sa_calced')
        return qs 
Example 14
Project: graphene-django   Author: graphql-python   File: test_converter.py    (license) View Source Project 6 votes vote down vote up
def test_field_with_choices_convert_enum():
    field = models.CharField(help_text='Language', choices=(
        ('es', 'Spanish'),
        ('en', 'English')
    ))

    class TranslatedModel(models.Model):
        language = field

        class Meta:
            app_label = 'test'

    graphene_type = convert_django_field_with_choices(field)
    assert isinstance(graphene_type, graphene.Enum)
    assert graphene_type._meta.name == 'TranslatedModelLanguage'
    assert graphene_type._meta.enum.__members__['ES'].value == 'es'
    assert graphene_type._meta.enum.__members__['ES'].description == 'Spanish'
    assert graphene_type._meta.enum.__members__['EN'].value == 'en'
    assert graphene_type._meta.enum.__members__['EN'].description == 'English' 
Example 15
Project: covart-web   Author: cyliang   File: views.py    (license) View Source Project 6 votes vote down vote up
def get_queryset(self):
        empty_str = ExpressionWrapper(V(''), output_field=CharField())
        future_meeting = models.MeetingHistory.objects.latest('date')

        return models.PresentHistory.objects.values(
            date=F('meeting__date'),
            presentation_type=F('present_type'),
            presenter_name=F('presenter__name'),
            present_content=F('content'),
        ).exclude(meeting__date=future_meeting.date).order_by().union(
            models.MeetingSkip.objects.all().values(
                'date',
                presentation_type=Concat(V('Postponed: '), 'reason'),
                presenter_name=empty_str,
                present_content=empty_str,
            ).filter(date__lte=date.today()).order_by()
        ).order_by('-date') 
Example 16
Project: django-binder   Author: CodeYellowBV   File: views.py    (license) View Source Project 6 votes vote down vote up
def field_needs_nullability_check(self, field):
		if isinstance(field, (models.CharField, models.TextField)):
			if field.blank and not field.null:
				return True

		return False



	# Deserialize JSON to Django Model objects.
	# obj: Model object to update (for PUT), newly created object (for POST)
	# values: Python dict of {field name: value} (parsed JSON)
	# Output: Python dict representation of the updated object 
Example 17
Project: django-tsvector-field   Author: damoti   File: test_querying.py    (license) View Source Project 6 votes vote down vote up
def setUp(self):

        class TextDocument(models.Model):
            title = models.CharField(max_length=128)
            body = models.TextField()
            search = SearchVectorField([
                WeightedColumn('title', 'A'),
                WeightedColumn('body', 'D'),
            ], 'english')

        with DatabaseSchemaEditor(connection) as schema_editor:
            schema_editor.create_model(TextDocument)

        TextDocument.objects.create(
            title="My hovercraft is full of eels.",
            body="Spam! Spam! Spam! Spam! Spam! Spam!",
        )
        TextDocument.objects.create(
            title="Spam! Spam! Spam! Spam! Spam! Spam!",
            body="My hovercraft is full of eels."
        )
        self.objects = TextDocument.objects 
Example 18
Project: django-tsvector-field   Author: damoti   File: test_querying.py    (license) View Source Project 6 votes vote down vote up
def setUp(self):

        class TextDocument(models.Model):
            title = models.CharField(max_length=128)
            body = models.TextField()
            search = SearchVectorField([
                WeightedColumn('title', 'A'),
                WeightedColumn('body', 'D'),
            ], 'english')

        with DatabaseSchemaEditor(connection) as schema_editor:
            schema_editor.create_model(TextDocument)

        TextDocument.objects.create(
            title="My hovercraft is full of eels.",
            body="Spam! Spam! Spam! Spam! Spam! Spam!",
        )
        TextDocument.objects.create(
            title="Spam! Spam! Spam! Spam! Spam! Spam!",
            body="My hovercraft is full of eels."
        )
        self.objects = TextDocument.objects 
Example 19
Project: gougo   Author: amaozhao   File: tests.py    (license) View Source Project 6 votes vote down vote up
def test_get_real_instances(self):
        self.create_model2abcd()
        qs = Model2A.objects.all().non_polymorphic()

        # from queryset
        objects = qs.get_real_instances()
        self.assertEqual(repr(objects[0]), '<Model2A: id 1, field1 (CharField)>')
        self.assertEqual(repr(objects[1]), '<Model2B: id 2, field1 (CharField), field2 (CharField)>')
        self.assertEqual(repr(objects[2]), '<Model2C: id 3, field1 (CharField), field2 (CharField), field3 (CharField)>')
        self.assertEqual(repr(objects[3]), '<Model2D: id 4, field1 (CharField), field2 (CharField), field3 (CharField), field4 (CharField)>')

        # from a manual list
        objects = Model2A.objects.get_real_instances(list(qs))
        self.assertEqual(repr(objects[0]), '<Model2A: id 1, field1 (CharField)>')
        self.assertEqual(repr(objects[1]), '<Model2B: id 2, field1 (CharField), field2 (CharField)>')
        self.assertEqual(repr(objects[2]), '<Model2C: id 3, field1 (CharField), field2 (CharField), field3 (CharField)>')
        self.assertEqual(repr(objects[3]), '<Model2D: id 4, field1 (CharField), field2 (CharField), field3 (CharField), field4 (CharField)>') 
Example 20
Project: gougo   Author: amaozhao   File: tests.py    (license) View Source Project 6 votes vote down vote up
def test_instance_of_filter(self):
        self.create_model2abcd()

        objects = Model2A.objects.instance_of(Model2B)
        self.assertEqual(repr(objects[0]), '<Model2B: id 2, field1 (CharField), field2 (CharField)>')
        self.assertEqual(repr(objects[1]), '<Model2C: id 3, field1 (CharField), field2 (CharField), field3 (CharField)>')
        self.assertEqual(repr(objects[2]), '<Model2D: id 4, field1 (CharField), field2 (CharField), field3 (CharField), field4 (CharField)>')
        self.assertEqual(len(objects), 3)

        objects = Model2A.objects.filter(instance_of=Model2B)
        self.assertEqual(repr(objects[0]), '<Model2B: id 2, field1 (CharField), field2 (CharField)>')
        self.assertEqual(repr(objects[1]), '<Model2C: id 3, field1 (CharField), field2 (CharField), field3 (CharField)>')
        self.assertEqual(repr(objects[2]), '<Model2D: id 4, field1 (CharField), field2 (CharField), field3 (CharField), field4 (CharField)>')
        self.assertEqual(len(objects), 3)

        objects = Model2A.objects.filter(Q(instance_of=Model2B))
        self.assertEqual(repr(objects[0]), '<Model2B: id 2, field1 (CharField), field2 (CharField)>')
        self.assertEqual(repr(objects[1]), '<Model2C: id 3, field1 (CharField), field2 (CharField), field3 (CharField)>')
        self.assertEqual(repr(objects[2]), '<Model2D: id 4, field1 (CharField), field2 (CharField), field3 (CharField), field4 (CharField)>')
        self.assertEqual(len(objects), 3)

        objects = Model2A.objects.not_instance_of(Model2B)
        self.assertEqual(repr(objects[0]), '<Model2A: id 1, field1 (CharField)>')
        self.assertEqual(len(objects), 1) 
Example 21
Project: gougo   Author: amaozhao   File: folderadmin.py    (license) View Source Project 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 22
Project: cyphon   Author: dunbarcyber   File: models.py    (license) View Source Project 6 votes vote down vote up
def to_key_val(self):
        """Return a key, value pair for the name and type of field.

        Returns
        -------
        |dict|
            A |dict| item mapping the object's `field_name` to its
            `field_type` and `target_type` (if any). For example,
            `{'name': 'CharField (Keyword)'`.

        """
        if self.target_type:
            target = ' (%s)' % self.target_type
        else:
            target = ''
        return {self.field_name: self.field_type + target} 
Example 23
Project: omni-forms   Author: omni-digital   File: test_models.py    (license) View Source Project 6 votes vote down vote up
def test_get_field(self):
        """
        The _get_field method should return a form field instance
        """
        field_1 = self.omniform._get_field('title')
        field_2 = self.omniform._get_field('agree')
        field_3 = self.omniform._get_field('fictional')
        self.assertIsInstance(field_1, forms.CharField)
        self.assertIsInstance(field_1.widget, forms.TextInput)
        self.assertEqual(field_1.label, 'Please give us a title')
        self.assertTrue(field_1.required)
        self.assertIsInstance(field_2, forms.BooleanField)
        self.assertIsInstance(field_2.widget, forms.CheckboxInput)
        self.assertEqual(field_2.label, 'Please agree')
        self.assertTrue(field_2.required)
        self.assertIsNone(field_3) 
Example 24
Project: fakester   Author: pawelad   File: test_models.py    (MIT License) View Source Project 5 votes vote down vote up
def test_model_local_path_field(self):
        """Test model 'local_path' field"""
        field = self.model._meta.get_field('local_path')

        assert isinstance(field, models.CharField)
        assert field.verbose_name == 'local path'
        assert field.max_length == 256
        assert field.unique
        assert (
            field.error_messages['unique'] ==
            "Sorry, but this path is already taken."
        ) 
Example 25
Project: WPS-4th   Author: Fastcampus-WPS   File: models.py    (license) View Source Project 5 votes vote down vote up
def __str__(self):
        return '{}{}'.format(
            self.last_name,
            self.first_name,
        )
    # CHOICES_USER_TYPE = (
    #     ('django', 'Django'),
    #     ('facebook', 'Facebook'),
    # )
    # social_id = models.CharField(max_length=100, blank=True)
    # user_type = models.CharField(
    #     max_length=15,
    #     choices=CHOICES_USER_TYPE,
    #     default=CHOICES_USER_TYPE[0][0]
    # ) 
Example 26
Project: django-datawatch   Author: RegioHelden   File: querysets.py    (MIT License) View Source Project 5 votes vote down vote up
def with_status_name(self):
        case = Case(output_field=models.CharField())
        for status_value in self.model.STATUS._db_values:
            case.cases.append(
                When(status=status_value, then=Value(str(self.model.STATUS[status_value]))),
            )
        return self.annotate(status_name=case) 
Example 27
Project: CodingDojo   Author: ComputerSocietyUNB   File: models.py    (license) View Source Project 5 votes vote down vote up
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30)) 
Example 28
Project: NarshaTech   Author: KimJangHyeon   File: models.py    (license) View Source Project 5 votes vote down vote up
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30)) 
Example 29
Project: django-modeltrans   Author: zostera   File: test_translating.py    (license) View Source Project 5 votes vote down vote up
def test_translate_bad_required_language(self):
        class A(models.Model):
            title = models.CharField(max_length=100)

            i18n = TranslationField(fields=('title', ), required_languages=('es', ))

            class Meta:
                app_label = 'django-modeltrans_tests'

        expected_message = (
            'Language "es" is in required_languages on '
            'Model "A" but not in settings.MODELTRANS_AVAILABLE_LANGUAGES.'
        )
        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
            translate_model(A) 
Example 30
Project: django-modeltrans   Author: zostera   File: test_translating.py    (license) View Source Project 5 votes vote down vote up
def test_translate_model_with_custom_manager(self):
        '''
        Verify the MultiLingualManager gets mixed in properly
        '''
        class CustomQuerySet(models.query.QuerySet):
            pass

        class CustomManager(models.Manager):
            def get_queryset(self):
                return CustomQuerySet()

            def custom_method(self):
                return 'foo'

        class TestModel1(models.Model):
            name = models.CharField(max_length=100)

            i18n = TranslationField(fields=('name', ))

            objects = CustomManager()

            class Meta:
                app_label = 'django-modeltrans_tests'

        translate_model(TestModel1)

        self.assertIsInstance(TestModel1.objects, CustomManager)
        self.assertIsInstance(TestModel1.objects, MultilingualManager)

        self.assertEquals(TestModel1.objects.custom_method(), 'foo')
        self.assertIsInstance(TestModel1.objects.all(), MultilingualQuerySet) 
Example 31
Project: django-modeltrans   Author: zostera   File: test_translating.py    (license) View Source Project 5 votes vote down vote up
def test_translate_model_with_non_modeltrans_i18n_field(self):
        class TestModel3(models.Model):
            title = models.CharField(max_length=100)
            i18n = models.BooleanField()

            class Meta:
                app_label = 'django-modeltrans_tests'

        translate_model(TestModel3) 
Example 32
Project: django-modeltrans   Author: zostera   File: test_translating.py    (license) View Source Project 5 votes vote down vote up
def test_field_gets_original_validators(self):
        def validator(value):
            if value in (None, ''):
                return

            if int(value) < 20:
                raise ValidationError('must be equal to or greater than 20.')

        class TestModel5(models.Model):
            title = models.CharField(max_length=100, validators=[validator, ])

            i18n = TranslationField(fields=('title', ))

            class Meta:
                app_label = 'django-modeltrans_tests'

        translate_model(TestModel5)

        field = TestModel5._meta.get_field('title')
        self.assertTrue(validator in field.validators)

        field = TestModel5._meta.get_field('title_nl')
        self.assertTrue(validator in field.validators)

        m = TestModel5(title='22', title_nl='10')
        with self.assertRaises(ValidationError) as e:
            m.full_clean()

        self.assertEquals(list(e.exception), [
            ('title_nl', ['must be equal to or greater than 20.']),
        ]) 
Example 33
Project: django-modeltrans   Author: zostera   File: test_querysets.py    (license) View Source Project 5 votes vote down vote up
def test_order_by_fallback_chain(self):

        class TestObj(models.Model):
            title = models.CharField(max_length=100)
            i18n = TranslationField(fields=('title', ))

            class Meta:
                app_label = 'django-modeltrans_tests'

        translate_model(TestObj)

        with CreateTestModel(TestObj):
            TestObj.objects.bulk_create([
                TestObj(title='Falcon', title_nl='Valk'),
                TestObj(title='Frog', title_nl='Kikker', title_fr='Grenouilles', title_fy='Frosk'),
                TestObj(title='Fox', title_nl='Vos', title_fy='Foks'),
                TestObj(title='Gecko'),
                TestObj(title='Gerbil'),
                TestObj(title='Vulture', title_nl='Gier', title_fr='Vautour')
            ])

            # should use the 'default' fallback chain
            with override('nl'):
                qs = TestObj.objects.all().order_by('title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), ['Gecko', 'Gerbil', 'Gier', 'Kikker', 'Valk', 'Vos'])

            # should use the 'fy' fallback chain
            with override('fy'):
                expected = ['Foks', 'Frosk', 'Gecko', 'Gerbil', 'Gier', 'Valk']
                qs = TestObj.objects.all().order_by('title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), expected)

                expected.reverse()
                qs = TestObj.objects.all().order_by('-title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), expected)

            # should use the 'default' fallback chain
            with override('fr'):
                qs = TestObj.objects.all().order_by('title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), ['Falcon', 'Fox', 'Gecko', 'Gerbil', 'Grenouilles', 'Vautour']) 
Example 34
Project: CoBL-public   Author: lingdb   File: models.py    (license) View Source Project 5 votes vote down vote up
def to_python(self, value):
        if isinstance(value, models.CharField):
            return value
        if value is None:
            return ""
        return value 
Example 35
Project: Server   Author: malaonline   File: models.py    (license) View Source Project 5 votes vote down vote up
def to_python(self, value):
        """
        Gets value right out of the db or an instance, and changes it if its ``None``.
        """
        if isinstance(value, models.CharField):
            # If an instance, just return the instance.
            return value
        if value is None:
            # If db has NULL, convert it to ''.
            return ''

        # Otherwise, just return the value.
        return value 
Example 36
Project: blog_django   Author: chnpmy   File: filters.py    (license) View Source Project 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 37
Project: django-echoices   Author: mbourqui   File: fields.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, echoices, *args, order=None, **kwargs):
        self.echoices = echoices
        self.order = order
        kwargs['choices'] = self._get_sorted_choices()
        default = kwargs.get('default')
        if default:
            if not isinstance(default, self.echoices):
                raise AttributeError(
                    "Illegal default value: {}. Must be an instance of {}".format(default, self.echoices))
            kwargs['default'] = default.value
        # Parameters specific to some fields
        if issubclass(self.__class__, models.CharField):
            kwargs['max_length'] = echoices.max_value_length()
        super(self.__class__, self).__init__(*args, **kwargs) 
Example 38
Project: django-echoices   Author: mbourqui   File: fields.py    (license) View Source Project 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(self.__class__, self).deconstruct()
        # Drop the parameters set by our field
        del kwargs['choices']
        if issubclass(self.__class__, models.CharField):
            del kwargs['max_length']
        # Set the parameters in our non-trivial formats
        kwargs['echoices'] = self.echoices
        if self.has_default():
            kwargs['default'] = self.get_default()
        return name, path, args, kwargs 
Example 39
Project: python-mysql-pool   Author: LuciferJack   File: validation.py    (license) View Source Project 5 votes vote down vote up
def validate_field(self, errors, opts, f):
            """
            MySQL has the following field length restriction:
            No character (varchar) fields can have a length exceeding 255
            characters if they have a unique index on them.
            """
            varchar_fields = (models.CharField,
                              models.CommaSeparatedIntegerField,
                              models.SlugField)
            if isinstance(f, varchar_fields) and f.max_length > 255 and f.unique:
                msg = ('"%(name)s": %(cls)s cannot have a "max_length" greater '
                       'than 255 when using "unique=True".')
                errors.add(opts, msg % {'name': f.name,
                                        'cls': f.__class__.__name__}) 
Example 40
Project: csv_generator   Author: fatboystring   File: test_csv_generator_column_model.py    (license) View Source Project 5 votes vote down vote up
def test_column_heading_field(self):
        """
        The column_heading field should be defined
        """
        field = CsvGeneratorColumn._meta.get_field('column_heading')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertTrue(field.blank)
        self.assertTrue(field.null) 
Example 41
Project: csv_generator   Author: fatboystring   File: test_csv_generator_column_model.py    (license) View Source Project 5 votes vote down vote up
def test_model_field_field(self):
        """
        The model_field field should be defined
        """
        field = CsvGeneratorColumn._meta.get_field('model_field')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 42
Project: csv_generator   Author: fatboystring   File: test_csv_generator_model.py    (license) View Source Project 5 votes vote down vote up
def test_title_field(self):
        """
        The title field should be defined
        """
        field = CsvGenerator._meta.get_field('title')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 43
Project: DCRM   Author: 82Flex   File: models.py    (license) View Source Project 5 votes vote down vote up
def get_internal_type(self):
        return 'CharField' 
Example 44
Project: dream_blog   Author: fanlion   File: filters.py    (license) View Source Project 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 45
Project: MxOnline   Author: myTeemo   File: filters.py    (license) View Source Project 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 46
Project: djangoblog   Author: liuhuipy   File: filters.py    (license) View Source Project 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 47
Project: timed-backend   Author: adfinis-sygroup   File: views.py    (license) View Source Project 5 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 48
Project: timed-backend   Author: adfinis-sygroup   File: views.py    (license) View Source Project 5 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 49
Project: django-jsonattrs   Author: Cadasta   File: models.py    (license) View Source Project 5 votes vote down vote up
def create_attribute_types():
    create_attribute_type('boolean', 'Boolean', 'BooleanField',
                          validator_type='bool',
                          validator_re=r'true|false|True|False')

    create_attribute_type('text', 'Text', 'CharField',
                          validator_type='str')
    create_attribute_type('text_multiline', 'Multiline text', 'CharField',
                          validator_type='str',
                          widget='Textarea')

    create_attribute_type('date', 'Date', 'DateField')
    create_attribute_type('dateTime', 'Date and time', 'DateTimeField')
    create_attribute_type('time', 'Time', 'TimeField')

    create_attribute_type('integer', 'Integer', 'IntegerField',
                          validator_re=r'[-+]?\d+')
    create_attribute_type('decimal', 'Decimal number', 'DecimalField',
                          validator_re=r'[-+]?\d+(\.\d+)?')

    create_attribute_type('email', 'Email address', 'EmailField')
    create_attribute_type('url', 'URL', 'URLField')

    create_attribute_type('select_one', 'Select one:', 'ChoiceField')
    create_attribute_type('select_multiple', 'Select multiple:',
                          'MultipleChoiceField')
    create_attribute_type('foreign_key', 'Select one:', 'ModelChoiceField')


# Sigh.  Oh Python.  Really?  Why?  Is there really no other way to
# look up a class by name than to manually calculate the transitive
# closure of the subclass relationship starting from "object"? 
Example 50
Project: PonyConf   Author: PonyConf   File: models.py    (license) View Source Project 5 votes vote down vote up
def get_filter_url(self):
        return reverse('talk-list') + '?category=%d' % self.pk


#class Attendee(PonyConfModel):
#
#    user = models.ForeignKey(User, null=True)
#    name = models.CharField(max_length=64, blank=True, default="")
#    email = models.EmailField(blank=True, default="")
#
#    def get_name(self):
#        if self.user:
#            return str(self.user.profile)
#        else:
#            return self.name
#    get_name.short_description = _('Name')
#
#    def get_email(self):
#        if self.user:
#            return self.user.email
#        else:
#            return self.email
#    get_email.short_description = _('Email')
#
#    def __str__(self):
#        return self.get_name()