'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 1:[1]

If you want to use the colorpicker from django-colorfield in your templates (outside of Django admin) you just have to set the field to type CharField and pass the widget ColorWidget to it. That's it.

For your case that would be something like this:

class TodoForm(forms.Form):
    COLOR_CHOICES = ['#8b0000', '#ffff00', '#006400']
    text = forms.CharField(max_length=40, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter todo here', 'aria-label': 'Todo', 'aria-describedby': 'add-btn'}))
    priority = ColorField(widget=ColorWidget(attrs={'palette': COLOR_CHOICES}))

Note that you have to pass the COLOR_CHOICES as list as well as attribute to the ColorWidget with the key palette in order to have the color palette.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Smort