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

Viewed 365

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) 
2 Answers

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">

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.

Related