Exemplo n.º 1
0
class imageGraphSeries(models.Model):
    image_graph = models.ForeignKey("imageGraph")
    label_colour = RGBColorField()
    line_colour = RGBColorField()
    observation_type = models.ForeignKey("patients.NumericObservationType")
    other_observation_type = models.ForeignKey(
        "patients.NumericObservationType",
        null=True,
        blank=True,
        related_name="imagegraphseriesother")
    lower_value = models.FloatField()
    pixel_height = models.FloatField()
    order = models.IntegerField()
    decimal_places = models.IntegerField()
    upper_value = models.FloatField()
    label = models.CharField(max_length=200)
    latest_value = models.BooleanField()

    class Meta:
        ordering = ['order']

    def get_pos(self, v):
        return self.pixel_height * (v - self.lower_value) / (self.upper_value -
                                                             self.lower_value)

    def __unicode__(self):
        return "%s: %s" % (self.observation_type, self.label)
Exemplo n.º 2
0
class MarkRange(models.Model):
    name = models.CharField(max_length=50, default="Chillax Line")
    minimum_mark = models.FloatField(default=72.5, help_text="Minimum mark as a percentage from 0 to 100 (or higher)")
    active = models.BooleanField(default=True)
    color_light = RGBColorField(default='#BEFFFA', help_text='Color to be used in the light theme')
    color_dark = RGBColorField(default='#337AB7', help_text='Color to be used in the dark theme')
    days = models.CharField(
        validators=[validate_comma_separated_integer_list],
        max_length=13,
        help_text='Comma seperated list of weekdays that this range is active, where Monday=1 and Sunday=7. \
                   E.g.: "1,3,5" for M, W, F.',
        default="1,2,3,4,5,6,7"
    )
    courses = models.ManyToManyField(
        "courses.course",
        blank=True,
        help_text="Which courses this field is relevant to; If left blank it will apply to all courses."
    )

    objects = MarkRangeManager()

    class Meta:
        ordering = ['minimum_mark']

    def __str__(self):
        return self.name + " (" + str(self.minimum_mark) + "%)"
Exemplo n.º 3
0
class Venue(models.Model):
    name = models.CharField(max_length=200)
    address = models.ForeignKey(Address)
    image = models.ImageField(upload_to='showgrid/img/venues/')
    website = models.URLField()
    description = models.TextField(default="This is a description")
    twitter_url = models.CharField(max_length=200, default=None)
    facebook_url = models.CharField(max_length=200, default=None)
    phone_regex = RegexValidator(
        regex=r'^\+?1?\d{9,15}$',
        message=
        "Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
    )
    phone = models.CharField(validators=[phone_regex],
                             blank=True,
                             null=True,
                             max_length=255)  # validators should be a list

    primary_color = RGBColorField()
    secondary_color = RGBColorField()
    accent_color = RGBColorField()
    # Sign-post for if venue is open or not
    opened = models.BooleanField(default=True)

    #extract meta_data

    # Auto-fill URL for calendars without unique links
    autofill = models.CharField(max_length=200, blank=True)
    age = models.PositiveSmallIntegerField(default=0, blank=True)

    def __unicode__(self):
        return self.name

    @property
    def alphabetical_title(self):
        name = self.name
        starts_with_flags = ['the ', 'an ', 'a ']

        for flag in starts_with_flags:
            if name.lower().startswith(flag):
                return "%s, %s" % (name[len(flag):], name[:len(flag) - 1])
        else:
            pass

        return self.name

    def json(self):
        return {
            'description': self.description,
            'twitter': self.twitter_url,
            'facebook': self.facebook_url,
            'id': self.id,
            'name': self.name,
            'website': self.website,
            'image': self.image.url,
            'address': self.address.json(),
            'primary_color': self.primary_color,
            'secondary_color': self.secondary_color,
            'accent_color': self.accent_color,
        }
Exemplo n.º 4
0
class BasePage(models.Model):
    headerImage = models.ImageField()
    background_color = RGBColorField()
    colorButton = RGBColorField(default='#17a2b8')

    class Meta:
        verbose_name_plural = "BasePage"
        verbose_name = "BasePage"
Exemplo n.º 5
0
class Label(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.CharField(max_length=200, default="")
    background_color = RGBColorField(default="#ffffff")
    text_color = RGBColorField(default="#000000")

    def __str__(self):
        return self.text
Exemplo n.º 6
0
class imageGraphSeriesLine(models.Model):
    image_graph_series = models.ForeignKey("imageGraphSeries")
    value = models.FloatField()
    othervalue = models.FloatField(null=True, blank=True)
    label = models.BooleanField()
    linethickness = models.FloatField(null=True, blank=True)
    label_colour = RGBColorField()
    line_colour = RGBColorField()
Exemplo n.º 7
0
class Footer(models.Model):
    backColor = RGBColorField(default='#f8f9fa')
    fontColor = RGBColorField(default='#ffffff')
    text1 = HTMLField(null=True)
    text2 = HTMLField(null=True)

    class Meta:
        verbose_name_plural = "Footer"
        verbose_name = "Footer"
Exemplo n.º 8
0
class RadarColorConversion(models.Model):
    original_color = RGBColorField(verbose_name='colore iniziale')
    converted_color = RGBColorField(verbose_name='colore finale')
    tolerance = models.IntegerField('tolleranza')

    class Meta:
        verbose_name = "Conversione colore radar"
        verbose_name_plural = "Conversioni colori radar"

    def __str__(self):
        return '%s - %s' % (self.original_color, str(self.converted_color))
Exemplo n.º 9
0
class Tag(models.Model):
    """
    Model for post tags
    """
    name = models.CharField(max_length=50, db_index=True)
    slug = models.SlugField(max_length=50, db_index=True)
    description = models.CharField(max_length=200,
                                   null=True,
                                   default=None,
                                   blank=True)

    icon_image = models.ImageField(upload_to="blog/tags/icons/",
                                   null=True,
                                   blank=True,
                                   default=None)
    color = RGBColorField(null=True, default=None, blank=True)
    font_color = RGBColorField(null=False, default="#000000")

    search_terms = ListField(null=True,
                             blank=True,
                             default=None,
                             verbose_name="Search Terms")

    _category = models.CharField(max_length=1, null=False)

    # - Meta classes and dunder methods

    class Meta:
        ordering = ('name', )

    def __str__(self):
        return self.name

    def __unicode__(self):
        return '%s' % self.name

    # - Methods

    def get_category_from_name(self):
        """Determine _category tag from objects name"""
        ret = self.name[0].upper()
        if ret not in string.ascii_uppercase:
            return "#"
        return ret

    # - Utility methods

    def save(self, *args, **kwargs):
        """Override to get _category trait on save"""
        self._category = self.get_category_from_name()
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('view_blog_tag', kwargs={'slug': self.slug})
Exemplo n.º 10
0
class lead_status(models.Model):
    status_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50)
    background_color = RGBColorField(colors=['#FF0000', '#00FF00', '#0000FF'])
    text_color = RGBColorField(colors=['#FF0000', '#00FF00', '#0000FF'])
    total_lead = models.IntegerField(default=0)
    user = models.CharField(max_length=50, default='SUPERADMIN')
    status = models.CharField(max_length=20, choices=status_choices, default='1')
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.name)
Exemplo n.º 11
0
class Navbar(models.Model):
    textMain = models.CharField(max_length=20)
    text1 = models.CharField(max_length=20)
    text2 = models.CharField(max_length=20)
    text3 = models.CharField(max_length=20)
    text4 = models.CharField(max_length=20)
    text5 = models.CharField(max_length=20, null=True)
    color = RGBColorField(default='#f8f9fa')
    fontColor = RGBColorField(default='#ffffff')

    class Meta:
        verbose_name_plural = "Navbar"
        verbose_name = "Navbar"
Exemplo n.º 12
0
class Badges(models.Model):
    badge_color = RGBColorField(default='#ffffff', null=True, blank=True)
    badge_text_color = RGBColorField(default='#000000', null=True, blank=True)
    badge_text = TextField(blank=True)

    panels = [
        FieldPanel('badge_color'),
        FieldPanel('badge_text_color'),
        FieldPanel('badge_text')
    ]

    class Meta:
        abstract = True
Exemplo n.º 13
0
class Producto(ModeloBase):
    nombre = models.CharField(max_length=50, null=False, blank=False)
    descripcion = models.TextField(max_length=40, null=False, blank=True)
    marca = models.CharField(max_length=50, blank=False, null=False)
    color = RGBColorField(colors=['#FF0000', '#00FF00', '#0000FF'])
    precio_comprar = models.PositiveIntegerField(
        default=0,
        validators=[MinValueValidator(0),
                    MaxValueValidator(1000**3)])
    precio_venta = models.IntegerField(
        null=False,
        blank=False,
        validators=[MinValueValidator(0),
                    MaxValueValidator(1000**3)])
    numero_talla = models.CharField(max_length=6)
    codigo = models.PositiveIntegerField(unique=True)
    tipo_tela = models.CharField(max_length=10)
    descuento = models.PositiveIntegerField(
        default=0, validators=[MinValueValidator(0),
                               MaxValueValidator(99)])
    imagen = models.ImageField()
    cantidad = models.IntegerField(default=0, null=False, blank=False)

    def __str__(self):

        return self.nombre

    class Meta:
        verbose_name = 'Producto'
        verbose_name_plural = 'Productos'
Exemplo n.º 14
0
class Category(models.Model):
    name = models.CharField(max_length=20)
    color = RGBColorField(null=True)
    community = models.ForeignKey(Community,
                                  blank=True,
                                  null=True,
                                  on_delete=models.CASCADE)

    def can_edit(self, user):
        if self.community is None:
            return user.is_authenticated and user.is_osr_admin()
        else:
            return self.community.is_admin(user)

    def __str__(self):
        return self.name

    def get_redirect_url(self):
        """
        Get the url to redirect with after editing or deleting the event
        """
        if self.community is None:
            return reverse('calendar:admin_cal_event_list')
        else:
            return reverse('community:community_page',
                           kwargs={'slug': self.community.slug})
Exemplo n.º 15
0
class Category(models.Model):
    """A category of the shop."""

    name = models.CharField(max_length=255)
    image = models.FileField(blank=True,
                             null=True,
                             upload_to=UploadHashedTo('categories'))
    color = RGBColorField(blank=True, null=True, default="#000000")
    order = models.IntegerField(default=9999)

    def clean(self):
        """Clean the model."""
        if self.color == '#000000':
            self.color = None

    def color_categorie_or_default(self):
        """Return the color of the item or of category if not existing."""
        if self.color:
            return self.color
        return config.DEFAULT_ITEM_COLOR

    def __str__(self):
        """Return the string representation of a Category."""
        return "{name}".format(**self.__dict__)

    class Meta:
        ordering = ('order', )
        verbose_name_plural = "Categories"
Exemplo n.º 16
0
class Category(models.Model):
    name = models.CharField(max_length=30)
    color = RGBColorField()
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.name
Exemplo n.º 17
0
class TalkCategory(models.Model): # type of talk (conf 30min, 1h, stand, …)
    site = models.ForeignKey(Site, on_delete=models.CASCADE)
    name = models.CharField(max_length=64)
    duration = models.PositiveIntegerField(default=0, verbose_name=_('Default duration (min)'))
    color = RGBColorField(default='#ffffff', verbose_name=_("Color on program"))
    label = models.CharField(max_length=64, verbose_name=_("Label on program"), blank=True, default="")
    opening_date = models.DateTimeField(null=True, blank=True, default=None)
    closing_date = models.DateTimeField(null=True, blank=True, default=None)

    def is_open(self):
        now = timezone.now()
        if self.opening_date and now < self.opening_date:
            return False
        if self.closing_date and now > self.closing_date:
            return False
        return True

    class Meta:
        unique_together = ('site', 'name')
        ordering = ('pk',)
        verbose_name = "category"
        verbose_name_plural = "categories"

    def __str__(self):
        return ugettext(self.name)

    def get_absolute_url(self):
        return reverse('category-list')

    def get_filter_url(self):
        return reverse('talk-list') + '?category=%d' % self.pk
Exemplo n.º 18
0
class Event(models.Model):

    site = models.ForeignKey(Site, on_delete=models.CASCADE)
    name = models.CharField(max_length=64)
    duration = models.PositiveIntegerField(
        default=0, verbose_name=_('Default duration (min)'))
    color = RGBColorField(default='#ffffff',
                          verbose_name=_("Color on program"))
    label = models.CharField(max_length=64,
                             verbose_name=_("Label on program"),
                             blank=True,
                             default="")
    opening_date = models.DateTimeField(null=True, blank=True, default=None)
    closing_date = models.DateTimeField(null=True, blank=True, default=None)

    def is_open(self):
        now = timezone.now()
        if self.opening_date and now < self.opening_date:
            return False
        if self.closing_date and now > self.closing_date:
            return False
        return True

    class Meta:
        unique_together = ('site', 'name')
        ordering = ('pk', )

    def __str__(self):
        return ugettext(self.name)

    def get_absolute_url(self):
        return reverse('list-talks') + '?kind=%d' % self.pk
Exemplo n.º 19
0
class Note(models.Model):
    user = models.ForeignKey(User,
                             on_delete=models.CASCADE,
                             to_field='username',
                             related_name='NoteUser')
    title = models.CharField(max_length=25, blank=True, null=True)
    note = models.TextField(blank=True, null=True)
    urls = models.URLField(blank=True, null=True)
    image = models.ImageField(upload_to='static/images',
                              max_length=255,
                              null=True,
                              blank=True)
    reminder = models.TimeField(auto_now_add=False,
                                auto_now=False,
                                null=True,
                                blank=True)
    archives = models.BooleanField(default=False)
    trash = models.BooleanField(default=False)
    pin = models.BooleanField(default=False)
    label = ArrayField(models.CharField(max_length=120, blank=True, null=True),
                       null=True,
                       blank=True)
    color = RGBColorField(default='#ffffff')
    collaborators = models.ManyToManyField(User, blank=True)

    class Meta:
        ordering = ['-pin', '-id']

    def __str__(self):
        return self.title
Exemplo n.º 20
0
class Chat_Widget_Customization(models.Model):
    #Chat_Widget_Customization id
    cwc_id = models.AutoField(primary_key=True)
    #bot id
    bot_id = models.ForeignKey(Bot_Details, on_delete=models.CASCADE)
    #color_chat_bot
    clr_cht_bt = RGBColorField()
    # default_icon_for_bots
    dflt_icn_fr_bts = models.ForeignKey(Image_Gallery,
                                        on_delete=models.CASCADE,
                                        null=True,
                                        blank=True)
    #custom_icon_for_bots
    upld_cstm_icon = models.ImageField(upload_to='images/',
                                       blank=True,
                                       null=True)
    # widget_position_on_the_screen
    wdgt_pos_on_the_scrn = models.CharField(
        max_length=100, choices=WIDGET_POSITION_ON_THE_SCREEN, default='Left')
    # notification_sound_for_bot
    ntn_snd_fr_bt = models.CharField(max_length=100,
                                     choices=NOTIFICATION_SOUND_FOR_BOT,
                                     default='First')
    #show the modefin branding indicator
    mfn_shwg_indct = models.BooleanField(choices=BOOL_CHOICES, default=True)

    def __str__(self):
        return str(self.cwc_id)
Exemplo n.º 21
0
class Notes(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user')
    title = models.CharField(max_length=500, blank=True, )
    note = models.CharField(max_length=500, )
    image = models.ImageField(max_length=500, blank=True, null=True, upload_to="media")
    is_archive = models.BooleanField("is_archived", default=False)
    is_trashed = models.BooleanField("delete_note", default=False)
    label = models.ManyToManyField(Label, related_name="label", blank=True)
    collaborators = models.ManyToManyField(User, related_name='collaborators', blank=True)
    is_copied = models.BooleanField("make a copy", default=False)
    checkbox = models.BooleanField("check box", default=False)
    is_pined = models.BooleanField("is pinned", default=False)
    url = models.URLField("url", blank=True)
    reminder = models.DateTimeField(blank=True, null=True)
    color = RGBColorField(colors=['#FF0000', '#00FF00', '#0000FF'], blank=True, null=True)

    def __str__(self):
        return self.note

    # def __eq__(self, other):
    #     if isinstance(other, Notes):
    #         return self.note == other.note
    #     return "cannot equalize different classes"

    def __repr__(self):
        return "Note({!r},{!r},{!r})".format(self.user, self.title, self.note)

    class Meta:
        """
        name is given which will be displayed in admin page
        """
        verbose_name = 'Note'
        verbose_name_plural = 'Notes'
Exemplo n.º 22
0
class a_box(models.Model):
    name = models.CharField(max_length=50)
    color = RGBColorField(colors=['#FF0000', '#00FF00', '#0000FF'])
    depth = models.FloatField()
    height = models.FloatField()
    width = models.FloatField()
    src = models.CharField(max_length=100)
Exemplo n.º 23
0
class ToolTaxonomy(TagTreeModel):
    """A generic way of describing a tool, the top level is the base taxonomy"""

    # order = models.IntegerField(blank=False, default=0)

    # Published state
    # Allows users to submit new taxonomies that are evaluated and approved
    class State(Catalog):
        _attrs = "value", "label"
        in_review = 0, _("in review")
        approved = 1, _("approved")
        rejected = 2, _("rejected")

    state = models.PositiveSmallIntegerField(
        _("State"), choices=State._zip("value", "label"), default=State.in_review.value
    )

    color = RGBColorField(null=True)

    class Meta:
        verbose_name = _("Tool Taxonomy")
        verbose_name_plural = _("Tool Taxonomies")

    class TagMeta:
        force_lowercase = False
        space_delimiter = False

    def get_color(self):
        if not self.color and self.parent:
            # try to get color from parent (this can cascade)
            return self.parent.get_color()
        else:
            return self.color
Exemplo n.º 24
0
class Tag(models.Model):
    """
    Represents a Tag that describes a characteristic
    """
    name = models.CharField(max_length=50)
    color = RGBColorField(default='#FF0000')

    def __str__(self):
        return self.name

    def get_color_lightness(self):
        """
        Returns the lightness of the Tag's color, calculated using RGB values
        """
        color_string = self.color.__str__()
        red = int(color_string[1:3], 16)
        green = int(color_string[3:5], 16)
        blue = int(color_string[5:7], 16)
        return (0.2126 * red + 0.7152 * green + 0.0722 * blue)

    def is_light_color(self):
        """
        Returns True if the Tag's lightness is above the 'light color' threshold
        """
        return self.get_color_lightness() > 127

    def get_absolute_url(self):
        """
        Returns an absolute URL for editing an instance of a Tag
        """
        return reverse("restaurant_tracker:tag_edit", kwargs={"pk": self.pk})
Exemplo n.º 25
0
class ObservationGraphSeries(models.Model):
    observation_graph = models.ForeignKey("ObservationGraph")
    observation_type = models.ForeignKey("patients.NumericObservationType")
    colour = RGBColorField()

    def __unicode__(self):
        return "%s: %s" % (self.observation_graph, self.observation_type)
Exemplo n.º 26
0
class Tag(models.Model):
    label = models.CharField(db_index=True,
                             max_length=128,
                             unique=True,
                             verbose_name=_('Label'))
    color = RGBColorField(verbose_name=_('Color'))
    documents = models.ManyToManyField(Document,
                                       related_name='tags',
                                       verbose_name=_('Documents'))

    def __str__(self):
        return self.label

    def get_absolute_url(self):
        return reverse('tags:tag_tagged_item_list', args=(str(self.pk), ))

    class Meta:
        ordering = ('label', )
        verbose_name = _('Tag')
        verbose_name_plural = _('Tags')

    def get_document_count(self, user):
        queryset = AccessControlList.objects.filter_by_access(
            permission_document_view, user, queryset=self.documents)

        return queryset.count()
class Theme(models.Model):
    """Feature categories"""
    name = models.CharField(max_length=128)
    color = RGBColorField(default='#4a62b1')

    def __str__(self):
        return self.name
Exemplo n.º 28
0
class Habit(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(
        null=True,
        blank=True,
    )
    schedule = models.CharField(
        default='daily',
        max_length=20,
        choices=[
            ('daily', 'Daily'),
            ('weekly', 'Weekly'),
            ('monthly', 'Monthly'),
        ],
    )
    current_streak = models.PositiveIntegerField(default=0)
    longest_streak = models.PositiveIntegerField(default=0)
    last_log_entry = models.DateTimeField(null=True)
    created = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    status = models.CharField(
        max_length=20,
        choices=[
            ('open', 'Open'),
            ('achieved', 'Achieved'),
        ],
    )
    color = RGBColorField(default='#663399', )
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
Exemplo n.º 29
0
class MapZone(models.Model):
    title = RichTextField(max_length=1024, verbose_name="nome della zona")

    color = RGBColorField(
        blank=True,
        null=True,
    )

    floor = models.CharField(max_length=1024,
                             blank=True,
                             null=True,
                             verbose_name="piano")

    tag = models.CharField(max_length=1024,
                           blank=True,
                           null=True,
                           verbose_name="tag identificativo")

    description = RichTextField(max_length=1024,
                                blank=True,
                                null=True,
                                verbose_name="descrizione")

    class Meta:
        verbose_name = 'Zona della mappa'
        verbose_name_plural = 'Zone della mappa'

    def __str__(self):
        return "MapZone " + str(self.id) + ' (' + \
               str(self.tag) + ') '
Exemplo n.º 30
0
class Continent(models.Model):
    name = models.CharField(max_length=20, unique=True)
    population = models.PositiveIntegerField()
    color = RGBColorField()

    def __str__(self):
        return self.name
Exemplo n.º 31
0
class TestRBGColorField(SimpleTestCase):
    def setUp(self):
        self.field = RGBColorField('verbose_name', default='#123445')
        self.field_with_colors = RGBColorField('verbose_name', colors=['#123445', '#000'])

    def test_validate_fails(self):
        self.assertRaises(ValidationError, self.field.clean, '', None)
        self.assertRaises(ValidationError, self.field.clean, '12', None)
        self.assertRaises(ValidationError, self.field.clean, 'GGGGGG', None)
        self.assertRaises(ValidationError, self.field.clean, '#GGGGGG', None)
        self.assertRaises(ValidationError, self.field.clean, 'GGG', None)
        self.assertRaises(ValidationError, self.field.clean, '#GGG', None)
        self.assertRaises(ValidationError, self.field.clean, '#1234567', None)

        self.assertRaisesMessage(
            ValidationError,
            'Ensure this value has at most 7 characters (it has 8).',
            self.field.clean, '#1234567', None
        )

    def test_validate_passes(self):
        self.assertEqual('#123445', self.field.clean('#123445', None))
        self.assertEqual('#123', self.field.clean('#123', None))
        self.assertEqual('#ABCDEF', self.field.clean('#ABCDEF', None))
        self.assertEqual('ABCDEF', self.field.clean('ABCDEF', None))
        self.assertEqual('123', self.field.clean('123', None))
        self.assertEqual('ABC', self.field.clean('ABC', None))

    def test_deconstruct(self):
        name, path, args, kwargs = self.field.deconstruct()
        self.assertIsNone(name)
        module, cls = path.rsplit('.', 1)
        field_class = getattr(sys.modules[module], cls)
        field_instance = field_class(*args, **kwargs)
        self.assertIsInstance(field_instance, self.field.__class__)
        self.assertEqual(field_instance.verbose_name, self.field.verbose_name)
        self.assertEqual(field_instance.default, self.field.default)
        self.assertIsNone(field_instance.colors)

    def test_deconstruct_with_colors(self):
        name, path, args, kwargs = self.field_with_colors.deconstruct()
        self.assertIsNone(name)
        module, cls = path.rsplit('.', 1)
        field_class = getattr(sys.modules[module], cls)
        field_instance = field_class(*args, **kwargs)
        self.assertIsInstance(field_instance, self.field_with_colors.__class__)
        self.assertEqual(field_instance.verbose_name, self.field.verbose_name)
        self.assertEqual(field_instance.default, NOT_PROVIDED)
        self.assertEqual(field_instance.colors, field_instance.colors)

    def test_formfield(self):
        formfield = self.field.formfield()
        self.assertIsInstance(formfield, forms.RegexField)
        self.assertIsInstance(formfield.widget, ColorFieldWidget)
        self.assertEqual(formfield.regex, RGB_REGEX)

    @patch('django.db.models.CharField.check')
    def test_check(self, charfield_check):
        test_apps = Apps()

        # do not test django's charfield checks
        charfield_check.side_effect = list

        # fine fields from setUp
        self.assertEqual(self.field.check(), [])
        self.assertEqual(self.field_with_colors.check(), [])

        # check type error
        class ColorsTypeSystemCheckTestModel(models.Model):
            color = RGBColorField(colors='#333,#ff00FF')

            class Meta:
                apps = test_apps
                app_label = 'colorful'

        self.assertEqual(ColorsTypeSystemCheckTestModel.check(), [
            Error(
                'colors is not iterable',
                hint='Define the colors param as list of strings.',
                obj=ColorsTypeSystemCheckTestModel._meta.get_field('color'),
                id='colorful.E001'
            )
        ])

        # check item error
        class ColorsItemSystemCheckTestModel(models.Model):
            color = RGBColorField(colors=['#'])

            class Meta:
                apps = test_apps
                app_label = 'colorful'

        self.assertEqual(ColorsItemSystemCheckTestModel.check(), [
            Error(
                'colors item validation error',
                hint='Each item of the colors param must be a valid color '
                     'string itself.',
                obj=ColorsItemSystemCheckTestModel._meta.get_field('color'),
                id='colorful.E002'
            )
        ])
Exemplo n.º 32
0
 def setUp(self):
     self.field = RGBColorField('verbose_name', default='#123445')
     self.field_with_colors = RGBColorField('verbose_name', colors=['#123445', '#000'])