Python django.db.models.BooleanField() Examples

The following are code examples for showing how to use django.db.models.BooleanField(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example 2
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example 3
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example 4
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_get_form_class(self):
        """
        The _get_form_class method should return a form class
        """
        form_class = self.omniform.get_form_class()
        self.assertTrue(issubclass(form_class, OmniFormBaseForm))
        self.assertEqual(form_class.__name__, 'OmniFormTestModel')
        form = form_class()

        # Test the title field
        self.assertIsInstance(form.fields['title'], forms.CharField)
        self.assertIsInstance(form.fields['title'].widget, forms.TextInput)
        self.assertEqual(form.fields['title'].label, 'Please give us a title')
        self.assertEqual(form.fields['title'].initial, 'Some title...')
        self.assertTrue(form.fields['title'].required)

        # Test the agree field
        self.assertIsInstance(form.fields['agree'], forms.BooleanField)
        self.assertIsInstance(form.fields['agree'].widget, forms.CheckboxInput)
        self.assertEqual(form.fields['agree'].label, 'Please agree')
        self.assertTrue(form.fields['agree'].initial)
        self.assertTrue(form.fields['agree'].required) 
Example 5
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_get_fields(self):
        """
        The method should return the correct fields as a dict
        """
        fields = self.omniform._get_fields()
        self.assertEqual(2, len(fields))

        # Test the title field
        self.assertIsInstance(fields['title'], forms.CharField)
        self.assertIsInstance(fields['title'].widget, forms.TextInput)
        self.assertEqual(fields['title'].label, 'Please give us a title')
        self.assertEqual(fields['title'].initial, 'Some title...')
        self.assertTrue(fields['title'].required)

        # Test the agree field
        self.assertIsInstance(fields['agree'], forms.BooleanField)
        self.assertIsInstance(fields['agree'].widget, forms.CheckboxInput)
        self.assertEqual(fields['agree'].label, 'Please agree')
        self.assertTrue(fields['agree'].initial)
        self.assertTrue(fields['agree'].required) 
Example 6
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 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 7
Project: openhatch   Author: campbe13   File: 0019_ashesh_add_favorite_field_to_tag.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding field 'Link_ProjectExp_Tag.favorite'
        db.add_column('profile_link_projectexp_tag', 'favorite', models.BooleanField(default=False))
        
        # Deleting field 'ProjectExp.favorite'
        db.delete_column('profile_projectexp', 'favorite')
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 22, 15, 9, 21, 939514)))
        
        # 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, 22, 15, 9, 22, 257788)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 22, 15, 9, 22, 322838))) 
Example 8
Project: openhatch   Author: campbe13   File: 0019_ashesh_add_favorite_field_to_tag.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def backwards(self, orm):
        
        # Deleting field 'Link_ProjectExp_Tag.favorite'
        db.delete_column('profile_link_projectexp_tag', 'favorite')
        
        # Adding field 'ProjectExp.favorite'
        db.add_column('profile_projectexp', 'favorite', models.BooleanField(default=0))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 22, 13, 44, 57, 89623)))
        
        # 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, 22, 13, 44, 57, 221866)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 22, 13, 44, 57, 165364))) 
Example 9
Project: openhatch   Author: campbe13   File: 0024_asheesh_add_person_ohloh_grab_completed.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding field 'Person.ohloh_grab_completed'
        db.add_column('profile_person', 'ohloh_grab_completed', models.BooleanField(default=False))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 18, 47, 19, 835058)))
        
        # Changing field 'Link_Person_Tag.time_record_was_created'
        db.alter_column('profile_link_person_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 18, 47, 20, 405392)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 18, 47, 20, 235527)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 18, 47, 20, 327376))) 
Example 10
Project: openhatch   Author: campbe13   File: 0025_asheesh_add_person_name_grabbed_from_ohloh.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding field 'Person.gotten_name_from_ohloh'
        db.add_column('profile_person', 'gotten_name_from_ohloh', models.BooleanField(default=False))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 30, 19, 58, 57, 424016)))
        
        # Changing field 'Link_Person_Tag.time_record_was_created'
        db.alter_column('profile_link_person_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 30, 19, 58, 58, 27599)))
        
        # 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, 30, 19, 58, 57, 840808)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 30, 19, 58, 57, 937712))) 
Example 11
Project: chattR   Author: patrickstocklin   File: utils.py    GNU General Public License v2.0 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 12
Project: opadmin   Author: cc0411   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example 13
Project: StormOnline   Author: stormsha   File: util.py    Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example 14
Project: django-atom   Author: ad-m   File: generate_factory.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_creator_for_field(self, name, field, model):
        if isinstance(field, models.AutoField):
            return False
        if isinstance(field, models.ForeignKey):
            return 'factory.SubFactory("{}")'.format(self.get_subfactory_path(field.related_model))
        if isinstance(field, models.CharField):
            return 'factory.Sequence("{0}-{1}-{{0}}".format)'.format(self.safe_name(model.__name__), self.safe_name(name))
        if isinstance(field, models.TextField):
            return "factory.fuzzy.FuzzyText()"
        if isinstance(field, (models.BooleanField, models.NullBooleanField)):
            return "factory.Sequence(lambda n: n % 2 == 0)"
        if isinstance(field, (models.IntegerField, models.SmallIntegerField)):
            return "factory.Sequence(lambda n: n)"
        if isinstance(field, (models.DateTimeField)):
            if field.__class__.__name__ in ['AutoLastModifiedField', 'AutoCreatedField']:  # django-model-utils fields
                return False
            return "factory.fuzzy.FuzzyNaiveDateTime(datetime.datetime(2008, 1, 1))"
        return "UNKNOWN  # TODO: {}".format(field.__class__.__name__) 
Example 15
Project: TESTGIT   Author: B-ROY   File: util.py    Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 16
Project: AneMo   Author: jspargo   File: utils.py    GNU General Public License v2.0 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 17
Project: GTDWeb   Author: lanbing510   File: utils.py    GNU General Public License v2.0 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 18
Project: liberator   Author: libscie   File: utils.py    Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 19
Project: banruo   Author: yingshang   File: utils.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # BooleanField needs special-case null-handling, so it comes before the
    # general null test.
    elif isinstance(field, models.BooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 20
Project: ops22   Author: spark8103   File: util.py    MIT License 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value) 
Example 21
Project: media-webapp   Author: uisautomation   File: models.py    MIT License 6 votes vote down vote up
def annotate_viewable(self, user, name='viewable'):
        """
        Annotate the query set with a boolean indicating if the user can view the item.

        """
        return self.annotate(**{
            name: models.Case(
                models.When(
                    Q(self._permission_condition('view_permission', user) |
                      self._permission_condition('channel__edit_permission', user)),
                    then=models.Value(True)
                ),
                default=models.Value(False),
                output_field=models.BooleanField()
            ),
        }) 
Example 22
Project: Fun5G   Author: OpenWinCon   File: utils.py    Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 23
Project: Vigtech-Services   Author: VigTech   File: utils.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 24
Project: DroidPot   Author: WhySoGeeky   File: utils.py    MIT License 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 25
Project: refarm-site   Author: fidals   File: search.py    MIT License 6 votes vote down vote up
def search(term: str, model_type: Union[models.Model, models.Manager, QuerySetType],
           lookups: list, ordering=None) -> QuerySetType:
    """
    Return search results based on a given model
    """
    def _get_Q(lookup):
        return Q(**{lookup: term})

    term = term.strip()
    query_set = _get_queryset(model_type)
    query = reduce(or_, map(_get_Q, lookups))

    return (
        query_set.filter(query, page__is_active=True)
        .annotate(
            is_name_start_by_term=Case(When(
                name__istartswith=term, then=Value(True)), default=Value(False),
                output_field=BooleanField())
        )
        .order_by(F('is_name_start_by_term').desc(), *ordering or ('name', ))
    ) 
Example 26
Project: PopularityBased-SearchEngine   Author: rsunder10   File: utils.py    MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 27
Project: news_proj   Author: TheoElia   File: utils.py    MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # BooleanField needs special-case null-handling, so it comes before the
    # general null test.
    elif isinstance(field, models.BooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 28
Project: mudong_blog   Author: mudong1991   File: util.py    GNU General Public License v2.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value) 
Example 29
Project: mudong_blog   Author: mudong1991   File: utils.py    GNU General Public License v2.0 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example 30
Project: Bookmark   Author: AnkurRyder   File: utils.py    MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example 31
Project: tri.query   Author: TriOptima   File: db_compat.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setup_db_compat_django():
    from django.db.models import IntegerField, FloatField, TextField, BooleanField, AutoField, CharField, DateField, DateTimeField, DecimalField, EmailField, URLField, TimeField, ForeignKey, ManyToOneRel, ManyToManyField, ManyToManyRel

    # The order here is significant because of inheritance structure. More specific must be below less specific.
    register_variable_factory(CharField, Shortcut()),
    register_variable_factory(URLField, Shortcut(call_target__attribute='url')),
    register_variable_factory(TimeField, Shortcut(call_target__attribute='time')),
    register_variable_factory(EmailField, Shortcut(call_target__attribute='email')),
    register_variable_factory(DecimalField, Shortcut(call_target__attribute='decimal')),
    register_variable_factory(DateField, Shortcut(call_target__attribute='date')),
    register_variable_factory(DateTimeField, Shortcut(call_target__attribute='datetime')),
    register_variable_factory(BooleanField, Shortcut(call_target__attribute='boolean')),
    register_variable_factory(TextField, Shortcut(call_target__attribute='text')),
    register_variable_factory(FloatField, Shortcut(call_target__attribute='float')),
    register_variable_factory(IntegerField, Shortcut(call_target__attribute='integer')),

    register_variable_factory(AutoField, Shortcut(call_target__attribute='integer', show=False))
    register_variable_factory(ManyToManyField, Shortcut(call_target__attribute='many_to_many'))

    register_variable_factory(ManyToOneRel, None),
    register_variable_factory(ManyToManyRel, None),
    register_variable_factory(ForeignKey, Shortcut(call_target__attribute='foreign_key')) 
Example 32
Project: xadmin_bugfix   Author: vip68   File: filters.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.BooleanField, models.NullBooleanField)) 
Example 33
Project: xadmin_bugfix   Author: vip68   File: util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example 34
Project: xadmin_bugfix   Author: vip68   File: export.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _format_value(self, o):
        if (o.field is None and getattr(o.attr, 'boolean', False)) or \
           (o.field and isinstance(o.field, (BooleanField, NullBooleanField))):
                value = o.value
        elif str(o.text).startswith("<span class='text-muted'>"):
            value = escape(str(o.text)[25:-7])
        else:
            value = escape(str(o.text))
        return value 
Example 35
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.BooleanField, models.NullBooleanField)) 
Example 36
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def _format_value(self, o):
        if (o.field is None and getattr(o.attr, 'boolean', False)) or \
           (o.field and isinstance(o.field, (BooleanField, NullBooleanField))):
                value = o.value
        elif str(o.text).startswith("<span class='text-muted'>"):
            value = escape(str(o.text)[25:-7])
        else:
            value = escape(str(o.text))
        return value 
Example 37
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.BooleanField, models.NullBooleanField)) 
Example 38
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.BooleanField, models.NullBooleanField)) 
Example 39
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def _format_value(self, o):
        if (o.field is None and getattr(o.attr, 'boolean', False)) or \
           (o.field and isinstance(o.field, (BooleanField, NullBooleanField))):
                value = o.value
        elif str(o.text).startswith("<span class='text-muted'>"):
            value = escape(str(o.text)[25:-7])
        else:
            value = escape(str(o.text))
        return value 
Example 40
Project: omni-forms   Author: omni-digital   File: models.py    MIT License 5 votes vote down vote up
def get_concrete_class_for_model_field(cls, model_field):
        """
        Method for getting a concrete model class to represent the type of form field required

        :param model_field: Model Field instance
        :return: OmniField subclass
        """
        field_mapping = {
            models.CharField: OmniCharField,
            models.TextField: OmniCharField,
            models.BooleanField: OmniBooleanField,
            models.NullBooleanField: OmniBooleanField,
            models.DateField: OmniDateField,
            models.DateTimeField: OmniDateTimeField,
            models.DecimalField: OmniDecimalField,
            models.EmailField: OmniEmailField,
            models.FloatField: OmniFloatField,
            models.IntegerField: OmniIntegerField,
            models.BigIntegerField: OmniIntegerField,
            models.PositiveIntegerField: OmniIntegerField,
            models.PositiveSmallIntegerField: OmniIntegerField,
            models.SmallIntegerField: OmniIntegerField,
            models.CommaSeparatedIntegerField: OmniCharField,
            models.TimeField: OmniTimeField,
            models.URLField: OmniUrlField,
            models.ForeignKey: OmniForeignKeyField,
            models.ManyToManyField: OmniManyToManyField,
            models.SlugField: OmniSlugField,
            models.FileField: OmniFileField,
            models.ImageField: OmniImageField,
            models.DurationField: OmniDurationField,
            models.GenericIPAddressField: OmniGenericIPAddressField
        }
        field_mapping.update(cls.get_custom_field_mapping())
        return field_mapping.get(model_field.__class__) 
Example 41
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_required_field(self):
        """
        The model should have a required field
        """
        field = OmniField._meta.get_field('required')
        self.assertIsInstance(field, models.BooleanField)
        self.assertFalse(field.default) 
Example 42
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_field_class(self):
        """
        The model should define the correct field class
        """
        self.assertEqual(OmniBooleanField.FIELD_CLASS, 'django.forms.BooleanField') 
Example 43
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_unpack_ipv4(self):
        """
        The model should have an unpack_ipv4 field
        """
        field = OmniGenericIPAddressField._meta.get_field('unpack_ipv4')
        self.assertIsInstance(field, models.BooleanField)
        self.assertTrue(field.blank)
        self.assertFalse(field.null)
        self.assertFalse(field.default) 
Example 44
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_allow_empty_file(self):
        """
        The model should not define a allow_empty_file field
        """
        field = OmniFileField._meta.get_field('allow_empty_file')
        self.assertIsInstance(field, models.BooleanField)
        self.assertFalse(field.default) 
Example 45
Project: django-echoices   Author: mbourqui   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_create_empty_instances(self):
        TestCharChoicesModel.objects.create()
        TestCharChoicesDefaultModel.objects.create()
        TestStrChoicesModel.objects.create()
        TestStrChoicesDefaultModel.objects.create()
        TestIntChoicesModel.objects.create()
        TestIntChoicesDefaultModel.objects.create()
        TestFloatChoicesModel.objects.create()
        TestFloatChoicesDefaultModel.objects.create()
        # NULL is not supported by BooleanField, but NullBooleanField does
        TestBoolChoicesDefaultModel.objects.create() 
Example 46
Project: django-echoices   Author: mbourqui   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_make_echoicefield(self):
        choice = make_echoicefield(ETestBoolChoices)
        self.assertTrue(choice.__class__.__bases__[0] is models.BooleanField)
        self.assertIs(choice.get_internal_type(), models.BooleanField.__name__) 
Example 47
Project: tri.form   Author: TriOptima   File: test_compat.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_defaults_factory_boolean():
    from django.db import models

    django_null_default = not models.BooleanField().null

    base = dict(parse_empty_string_as_none=django_null_default, display_name=None)

    assert field_defaults_factory(models.BooleanField(null=False, blank=False)) == merged(base, dict(parse_empty_string_as_none=False))
    assert field_defaults_factory(models.BooleanField(null=False, blank=True)) == merged(base, dict(parse_empty_string_as_none=False))

    assert field_defaults_factory(models.BooleanField(null=True, blank=False)) == base
    assert field_defaults_factory(models.BooleanField(null=True, blank=True)) == base 
Example 48
Project: tri.form   Author: TriOptima   File: compat.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_db_compat():
        from tri_form import register_field_factory
        from django.db.models import IntegerField, FloatField, TextField, BooleanField, AutoField, CharField, \
            DateField, DateTimeField, DecimalField, EmailField, URLField, TimeField, \
            ForeignKey, ManyToManyField, FileField, ManyToOneRel, ManyToManyRel, UUIDField

        # The order here is significant because of inheritance structure. More specific must be below less specific.
        register_field_factory(CharField, Shortcut())
        register_field_factory(UUIDField, Shortcut())
        register_field_factory(URLField, Shortcut(call_target__attribute='url'))
        register_field_factory(TimeField, Shortcut(call_target__attribute='time'))
        register_field_factory(EmailField, Shortcut(call_target__attribute='email'))
        register_field_factory(DecimalField, Shortcut(call_target__attribute='decimal'))
        register_field_factory(DateField, Shortcut(call_target__attribute='date'))
        register_field_factory(DateTimeField, Shortcut(call_target__attribute='datetime'))
        register_field_factory(
            BooleanField,
            lambda model_field, **kwargs: (
                Shortcut(call_target__attribute='boolean')
                if not model_field.null
                else Shortcut(call_target__attribute='boolean_tristate')
            )
        )
        register_field_factory(TextField, Shortcut(call_target__attribute='textarea'))
        register_field_factory(FloatField, Shortcut(call_target__attribute='float'))
        register_field_factory(IntegerField, Shortcut(call_target__attribute='integer'))
        register_field_factory(AutoField, Shortcut(call_target__attribute='integer', show=False))
        register_field_factory(ManyToOneRel, None)
        register_field_factory(ManyToManyRel, None)
        register_field_factory(FileField, Shortcut(call_target__attribute='file'))
        register_field_factory(ForeignKey, Shortcut(call_target__attribute='foreign_key'))
        register_field_factory(ManyToManyField, Shortcut(call_target__attribute='many_to_many')) 
Example 49
Project: tri.form   Author: TriOptima   File: compat.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def field_defaults_factory(model_field):
        from tri_form import capitalize
        from django.db.models import BooleanField
        r = {}
        if hasattr(model_field, 'verbose_name'):
            r['display_name'] = capitalize(model_field.verbose_name)

        if hasattr(model_field, 'null') and not isinstance(model_field, BooleanField):
            r['required'] = not model_field.null and not model_field.blank

        if hasattr(model_field, 'null'):
            r['parse_empty_string_as_none'] = model_field.null

        return r 
Example 50
Project: openhatch   Author: campbe13   File: 0020_asheesh_add_sourceforge_models.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Link_SF_Proj_Dude_FM'
        db.create_table('profile_link_sf_proj_dude_fm', (
            ('id', models.AutoField(primary_key=True)),
            ('person', models.ForeignKey(orm.SourceForgePerson)),
            ('project', models.ForeignKey(orm.SourceForgeProject)),
            ('is_admin', models.BooleanField(default=False)),
            ('position', models.CharField(max_length=200)),
            ('date_collected', models.DateTimeField()),
        ))
        db.send_create_signal('profile', ['Link_SF_Proj_Dude_FM'])
        
        # Adding model 'SourceForgeProject'
        db.create_table('profile_sourceforgeproject', (
            ('id', models.AutoField(primary_key=True)),
            ('unixname', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['SourceForgeProject'])
        
        # Adding model 'SourceForgePerson'
        db.create_table('profile_sourceforgeperson', (
            ('id', models.AutoField(primary_key=True)),
            ('username', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['SourceForgePerson'])
        
        # Adding field 'ProjectExp.favorite'
        db.add_column('profile_projectexp', 'favorite', models.BooleanField(default=False))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 25, 10, 24, 40, 465787)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 25, 10, 24, 40, 858041)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 25, 10, 24, 40, 948895)))
        
        # Creating unique_together for [person, project] on Link_SF_Proj_Dude_FM.
        db.create_unique('profile_link_sf_proj_dude_fm', ['person_id', 'project_id']) 
Example 51
Project: openhatch   Author: campbe13   File: 0033_ditch_favoriting_for_projectexps.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def backwards(self, orm):
        
        # Adding field 'ProjectExp.favorite'
        db.add_column('profile_projectexp', 'favorite', models.BooleanField(default=0)) 
Example 52
Project: openhatch   Author: campbe13   File: 0002_extend_person.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding field 'Person.last_touched'
        db.add_column('profile_person', 'last_touched', models.DateTimeField(null=True))
        
        # Adding field 'Person.last_polled'
        db.add_column('profile_person', 'last_polled', models.DateTimeField(null=True))
        
        # Adding field 'Person.time_record_was_created'
        db.add_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.date(2009, 6, 18)))
        
        # Adding field 'Person.poll_on_next_web_view'
        db.add_column('profile_person', 'poll_on_next_web_view', models.BooleanField(default=True)) 
Example 53
Project: openhatch   Author: campbe13   File: 0008_raffi_add_good_for_newcomers.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding field 'Bug.good_for_newcomers'
        db.add_column('search_bug', 'good_for_newcomers', models.BooleanField(default=False)) 
Example 54
Project: openhatch   Author: campbe13   File: 0009_add_icon_imagefield_to_project.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding field 'Project.icon'
        db.add_column('search_project', 'icon', orm['search.project:icon'])
        
        # Adding field 'Project.date_icon_was_fetched_from_ohloh'
        db.add_column('search_project', 'date_icon_was_fetched_from_ohloh', orm['search.project:date_icon_was_fetched_from_ohloh'])
        
        # Changing field 'Bug.project'
        # (to signature: django.db.models.fields.related.ForeignKey(to=orm['search.Project']))
        db.alter_column('search_bug', 'project_id', orm['search.bug:project'])
        
        # Changing field 'Bug.good_for_newcomers'
        # (to signature: django.db.models.fields.BooleanField(default=False, blank=True))
        db.alter_column('search_bug', 'good_for_newcomers', orm['search.bug:good_for_newcomers']) 
Example 55
Project: openhatch   Author: campbe13   File: 0009_add_icon_imagefield_to_project.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def backwards(self, orm):
        
        # Deleting field 'Project.icon'
        db.delete_column('search_project', 'icon')
        
        # Deleting field 'Project.date_icon_was_fetched_from_ohloh'
        db.delete_column('search_project', 'date_icon_was_fetched_from_ohloh')
        
        # Changing field 'Bug.project'
        # (to signature: models.ForeignKey(orm['search.Project']))
        db.alter_column('search_bug', 'project_id', orm['search.bug:project'])
        
        # Changing field 'Bug.good_for_newcomers'
        # (to signature: models.BooleanField(default=False))
        db.alter_column('search_bug', 'good_for_newcomers', orm['search.bug:good_for_newcomers']) 
Example 56
Project: opadmin   Author: cc0411   File: filters.py    GNU 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.BooleanField, models.NullBooleanField)) 
Example 57
Project: opadmin   Author: cc0411   File: export.py    GNU General Public License v3.0 5 votes vote down vote up
def _format_value(self, o):
        if (o.field is None and getattr(o.attr, 'boolean', False)) or \
           (o.field and isinstance(o.field, (BooleanField, NullBooleanField))):
                value = o.value
        elif str(o.text).startswith("<span class='text-muted'>"):
            value = escape(str(o.text)[25:-7])
        else:
            value = escape(str(o.text))
        return value 
Example 58
Project: StormOnline   Author: stormsha   File: filters.py    Apache License 2.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.BooleanField, models.NullBooleanField)) 
Example 59
Project: StormOnline   Author: stormsha   File: export.py    Apache License 2.0 5 votes vote down vote up
def _format_value(self, o):
        if (o.field is None and getattr(o.attr, 'boolean', False)) or \
           (o.field and isinstance(o.field, (BooleanField, NullBooleanField))):
                value = o.value
        elif str(o.text).startswith("<span class='text-muted'>"):
            value = escape(str(o.text)[25:-7])
        else:
            value = escape(str(o.text))
        return value 
Example 60
Project: django-idcops   Author: Wenvki   File: utils.py    Apache License 2.0 5 votes vote down vote up
def display_for_field(value, field, html=True, only_date=True):
    if getattr(field, 'flatchoices', None):
        if html and field.name == 'color' and value:
            return make_color_icon(value)
        return dict(field.flatchoices).get(value, '')
    elif html and (isinstance(field, (models.BooleanField, models.NullBooleanField))):
        return make_boolean_icon(value)
    elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
        boolchoice = {False: "否", True: "是"}
        return boolchoice.get(value)
    elif value is None:
        return ""
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.ForeignKey) and value:
        rel_obj = field.related_model.objects.get(pk=value)
        if html and COLOR_FK_FIELD and isinstance(rel_obj, Option):
            text_color = rel_obj.color
            if not text_color:
                text_color = 'text-info'
            safe_value = format_html(
                '<span class="text-{}">{}</span>', text_color, rel_obj.text)
            return safe_value
        return force_text(rel_obj)
    elif isinstance(field, models.TextField) and value:
        return force_text(value)
    elif isinstance(field, models.DateTimeField):
        if only_date:
            return formats.date_format(value)
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value) 
Example 61
Project: asso   Author: Diacamma2   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_search_doc_fields(cls):
        fields = []
        try:
            document_list = Season.current_season().document_set.all()
        except LucteriosException:
            document_list = []
        for doc_item in document_list:
            dbfield = BooleanField("%s > %s > %s" % (_('subscription'), _('documents needs'), doc_item.name))
            fields.append(('doc_%d' % doc_item.id, dbfield, 'subscription__docadherent__value', Q(subscription__docadherent__document=doc_item)))
        return fields 
Example 62
Project: ops22   Author: spark8103   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.BooleanField, models.NullBooleanField)) 
Example 63
Project: ops22   Author: spark8103   File: export.py    MIT License 5 votes vote down vote up
def _format_value(self, o):
        if (o.field is None and getattr(o.attr, 'boolean', False)) or \
           (o.field and isinstance(o.field, (BooleanField, NullBooleanField))):
                value = o.value
        elif str(o.text).startswith("<span class='text-muted'>"):
            value = escape(str(o.text)[25:-7])
        else:
            value = escape(str(o.text))
        return value 
Example 64
Project: media-webapp   Author: uisautomation   File: views.py    MIT License 5 votes vote down vote up
def filter_billing_account_qs(self, qs):
        """
        Filters a BillingAccount queryset so that only the appropriate objects are returned for the
        user, annotates the objects with any fields required by the serialisers and selects any
        related objects used by the serialisers.

        """
        # HACK: for the moment, billing accounts have no associated permissions so fake it so that
        # everyone can view them and no-one can edit them.
        return qs.annotate(
            viewable=models.Value(True, output_field=models.BooleanField()),
            editable=models.Value(False, output_field=models.BooleanField()),
        ) 
Example 65
Project: media-webapp   Author: uisautomation   File: models.py    MIT License 5 votes vote down vote up
def annotate_viewable(self, user, name='viewable'):
        """
        Annotate the query set with a boolean indicating if the user can view the item.

        """
        return self.annotate(**{
            name: models.Case(
                models.When(self._viewable_condition(user), then=models.Value(True)),
                default=models.Value(False),
                output_field=models.BooleanField()
            ),
        }) 
Example 66
Project: media-webapp   Author: uisautomation   File: models.py    MIT License 5 votes vote down vote up
def annotate_editable(self, user, name='editable'):
        """
        Annotate the query set with a boolean indicating if the user can edit the item.

        """
        return self.annotate(**{
            name: models.Case(
                models.When(self._editable_condition(user), then=models.Value(True)),
                default=models.Value(False),
                output_field=models.BooleanField()
            ),
        }) 
Example 67
Project: media-webapp   Author: uisautomation   File: models.py    MIT License 5 votes vote down vote up
def annotate_downloadable(self, user, name='downloadable_by_user'):
        """
        Annotate the query set with a boolean indicating if the user can download the item. To
        avoid clashing with the model's downloadable flag, the annotation is called
        "downloadable_by_user".

        """
        return self.annotate(**{
            name: models.Case(
                models.When(self._downloadable_condition(user), then=models.Value(True)),
                default=models.Value(False),
                output_field=models.BooleanField()
            ),
        }) 
Example 68
Project: media-webapp   Author: uisautomation   File: models.py    MIT License 5 votes vote down vote up
def annotate_viewable(self, user, name='viewable'):
        """
        Annotate the query set with a boolean indicating if the user can view the channel.

        This is always true but this method is provided for compatibility with code shared between
        media items and channels.

        """
        return self.annotate(**{name: models.Value(True, output_field=models.BooleanField())}) 
Example 69
Project: media-webapp   Author: uisautomation   File: models.py    MIT License 5 votes vote down vote up
def annotate_editable(self, user, name='editable'):
        """
        Annotate the query set with a boolean indicating if the user can edit the playlist.

        """
        return self.annotate(**{
            name: models.Case(
                models.When(
                    self._permission_condition('channel__edit_permission', user),
                    then=models.Value(True)
                ),
                default=models.Value(False),
                output_field=models.BooleanField()
            ),
        }) 
Example 70
Project: media-webapp   Author: uisautomation   File: models.py    MIT License 5 votes vote down vote up
def annotate_can_create_channels(self, user, name='can_create_channels'):
        """
        Annotate the query set with a boolean indicating if the user can create channels.

        """
        return self.annotate(**{
            name: models.Case(
                models.When(
                    Q(self._permission_condition('channel_create_permission', user)),
                    then=models.Value(True)
                ),
                default=models.Value(False),
                output_field=models.BooleanField()
            ),
        }) 
Example 71
Project: timed-backend   Author: adfinis-sygroup   File: serializers.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_verified(self, instance):
        queryset = instance["queryset"]
        queryset = queryset.annotate(
            verified=Case(
                When(verified_by_id__isnull=True, then=False),
                default=True,
                output_field=BooleanField(),
            )
        )
        instance["queryset"] = queryset
        return self._intersection(instance, "verified") 
Example 72
Project: reactivated   Author: silviogutierrez   File: types.py    MIT License 5 votes vote down vote up
def test_get_field_descriptor():
    descriptor, path = get_field_descriptor(models.Opera, ["has_piano_transcription"])
    assert isinstance(descriptor, django_models.BooleanField)
    assert path == ()

    descriptor, path = get_field_descriptor(models.Opera, ["composer"])
    assert isinstance(descriptor, django_models.ForeignKey)
    assert path == ()

    descriptor, path = get_field_descriptor(models.Opera, ["composer", "name"])
    assert isinstance(descriptor, django_models.CharField)
    assert path == (("composer", False),)

    descriptor, path = get_field_descriptor(
        models.Opera, ["composer", "countries", "name"]
    )
    assert isinstance(descriptor, django_models.CharField)
    assert path == (("composer", False), ("countries", True))

    descriptor, path = get_field_descriptor(
        models.Opera, ["composer", "composer_countries", "was_born"]
    )
    assert isinstance(descriptor, django_models.BooleanField)
    assert path == (("composer", False), ("composer_countries", True))

    descriptor, path = get_field_descriptor(models.Composer, ["countries"])
    assert isinstance(descriptor, django_models.ManyToManyField)
    assert path == () 
Example 73
Project: django-boolean-switch   Author: makeev   File: admin.py    MIT License 5 votes vote down vote up
def get_list_display(self, request):
        """
        Return a sequence containing the fields to be displayed on the
        changelist.
        """
        list_display = []
        for field_name in self.list_display:
            try:
                db_field = self.model._meta.get_field(field_name)
                if isinstance(db_field, BooleanField):
                    field_name = boolean_switch_field(db_field)
            except FieldDoesNotExist:
                pass
            list_display.append(field_name)
        return list_display 
Example 74
Project: mudong_blog   Author: mudong1991   File: filters.py    GNU General Public License v2.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.BooleanField, models.NullBooleanField)) 
Example 75
Project: mudong_blog   Author: mudong1991   File: export.py    GNU General Public License v2.0 5 votes vote down vote up
def _format_value(self, o):
        if (o.field is None and getattr(o.attr, 'boolean', False)) or \
           (o.field and isinstance(o.field, (BooleanField, NullBooleanField))):
                value = o.value
        elif str(o.text).startswith("<span class='text-muted'>"):
            value = escape(str(o.text)[25:-7])
        else:
            value = escape(str(o.text))
        return value 
Example 76
Project: karrot-backend   Author: yunity   File: models.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def with_conversation_access(self, user):
        # Note: this is needed if ConversationQuerySet.with_access is too slow
        # should contain the same logic
        return self.filter(
            Q(conversation__participants=user) |
            Q(conversation__group__groupmembership__user=user, conversation__is_group_public=True)
        ).annotate(
            has_conversation_access=Value(True, output_field=models.BooleanField())
            # This is not just an annotation, we use it because it results in a 'group by' clause
            # It is much faster then the alternative 'distinct' modifier
        ) 
Example 77
Project: news   Author: kuc2477   File: django.py    MIT License 5 votes vote down vote up
def create_schedule_abc(user_model=None):
    """Abstract base schedule model factory.

    :param user_model: User model to use as schedule owners.
    :type user_model: :class:`~news.models.AbstractModel`
        implemenatation
    :returns: A abstract base schedule model.
    :rtype: Abstract base django model of
        :class:`~news.models.AbstractSchedule` implementation.

    """
    user_model = user_model or settings.AUTH_USER_MODEL

    class AbstractBaseSchedule(models.Model, AbstractSchedule):
        owner = models.ForeignKey(
            user_model, related_name='schedules',
            db_index=True, blank=True, null=True,
        )

        url = models.URLField()
        cycle = models.IntegerField(default=DEFAULT_SCHEDULE_CYCLE)
        enabled = models.BooleanField(default=False)
        type = models.CharField(max_length=SCHEDULE_TYPE_MAX_LENGTH,
                                default=DEFAULT_SCHEDULE_TYPE)
        options = JSONField(default=DEFAULT_OPTIONS)

        class Meta:
            abstract = True
            unique_together = (('owner', 'url'),)

    return AbstractBaseSchedule 
Example 78
Project: autofactoryboy   Author: nickgashkov   File: compat.py    MIT License 5 votes vote down vote up
def get_not_blank_fields(fields):
    boolean_fields = {
        models.BooleanField,
        models.NullBooleanField,
    }

    return [f for f in fields if f.__class__ in boolean_fields or not f.blank] 
Example 79
Project: klever   Author: ldv-klever   File: serializers.py    Apache License 2.0 5 votes vote down vote up
def get_unknowns(self, instance):
        unknowns_data = {}

        # Marked/Unmarked unknowns
        unconfirmed_annotation = Case(
            When(markreport_set__type=ASSOCIATION_TYPE[2][0], then=True),
            default=False, output_field=BooleanField()
        )
        queryset = ReportUnknown.objects.filter(root=instance) \
            .values('component', 'markreport_set__problem') \
            .annotate(number=Count('id', distinct=True), unconfirmed=unconfirmed_annotation) \
            .values_list('component', 'markreport_set__problem', 'number', 'unconfirmed')
        for component, problem, number, unconfirmed in queryset:
            data_key = (component, 'Without marks' if problem is None or unconfirmed else problem)
            unknowns_data.setdefault(data_key, 0)
            unknowns_data[data_key] += number
        unknowns_list = list({
            'component': component, 'problem': problem,
            'number': unknowns_data[component, problem]
        } for component, problem in sorted(unknowns_data))

        # Total unknowns for each component
        queryset = ReportUnknown.objects.filter(root=instance) \
            .values('component').annotate(number=Count('id')) \
            .values_list('component', 'number').order_by('component')
        totals_list = list({'component': component, 'problem': 'Total', 'number': number}
                           for component, number in queryset)
        return unknowns_list + totals_list 
Example 80
Project: django-echoices   Author: mbourqui   File: fields.py    GNU General Public License v3.0 4 votes vote down vote up
def make_echoicefield(echoices, *args, klass_name=None, **kwargs):
    """
    Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values.

    Parameters
    ----------
    echoices : subclass of EChoice
    args
        Passed to the derived `models.Field`
    klass_name : str
        Give a specific name to the returned class.
        By default for Django < 1.9, the name will be 'EChoiceField'.
        By default for Django >= 1.9, the name will be the name of the enum appended with 'Field'.
    kwargs
        Passed to the derived `models.Field`

    Returns
    -------
    EChoiceField
        For Django>=1.9, the exact name of the returned Field is based on the name of the `echoices` with a suffixed
        'Field'. For older Django, the returned name of the class is `EChoiceField`.

    """
    assert issubclass(echoices, EChoice)
    value_type = echoices.__getvaluetype__()
    if value_type is str:
        cls_ = models.CharField
    elif value_type is int:
        cls_ = models.IntegerField
    elif value_type is float:
        cls_ = models.FloatField
    elif value_type is bool:
        cls_ = models.BooleanField
    else:
        raise NotImplementedError("Please open an issue if you wish your value type to be supported: "
                                  "https://github.com/mbourqui/django-echoices/issues/new")
    if klass_name and StrictVersion(django_version()) < StrictVersion('1.9.0'):
        warnings.warn("Django < 1.9 throws an 'ImportError' if the class name is not defined in the module. "
                      "The provided klass_name will be replaced by {}".format(EChoiceField.__name__), RuntimeWarning)
    klass_name = EChoiceField.__name__ if StrictVersion(django_version()) < StrictVersion('1.9.0') else \
        klass_name if klass_name else "{}Field".format(echoices.__name__)
    d = dict(cls_.__dict__)
    d.update(dict(EChoiceField.__dict__))
    return type(klass_name, (cls_,), d)(echoices, *args, **kwargs)

# TODO: MultipleEChoiceField