Search code examples
pythondjango

How to use django-colorfield in a forms.py file in django?


I'm trying to use Django-colorfield to create a drop-down from which a color can be selected. However, the priority section in the output just says <colorfield.fields.ColorField>.I tried this answer but it didn't work. Output, Code:

#models.py

from django.db import models
from colorfield.fields import ColorField

class Todo(models.Model):
    text = models.CharField(max_length=40)
    complete = models.BooleanField(default=False)
    COLOR_CHOICES = [
        ("#8b0000", "red"),
        ("#ffff00", "yellow"),
        ("#006400","green")
    ]

    priority = ColorField(choices=COLOR_CHOICES)
    
    
    def __str__(self):
        return self.text
#forms.py
from django import forms 
from colorfield.fields import ColorField
from .models import Todo


class TodoForm(forms.Form):
    text = forms.CharField(max_length=40,
    
        widget=forms.TextInput(
            attrs={'class' : 'form-control', 'placeholder' : 'Enter todo here', 'aria-label' : 'Todo', 'aria-describedby' : 'add-btn'}))


    COLOR_CHOICES = [
        ("#8b0000", "red"),
        ("#ffff00", "yellow"),
        ("#006400","green")
    ]

    priority = ColorField(choices=COLOR_CHOICES) 

Solution

  • The ColorField only works in Django Admin. If you would like a colorpicker in your template, I would suggest creating CharField, like:

    priority = models.CharField(max_length=7)
    

    Add in your template add either a JS plugin for showing a colorpicker or use the HTML5 colorpicker, for example:

    <input id="id_priority" maxlength="7" name="priority" type="color">