45π
I found the answer in the documentation:
The extra class in forms.py was not necessary
#form.py
from django.forms import ModelForm
from django.forms.widgets import TextInput
from .models import Category
class CategoryForm(ModelForm):
class Meta:
model = Category
fields = '__all__'
widgets = {
'color': TextInput(attrs={'type': 'color'}),
}
And in the admin:
#admin.py
...
from .forms import CategoryForm
...
class CategoryAdmin(admin.ModelAdmin):
form = CategoryForm
filter_horizontal = ('questions',)
fieldsets = (
(None, {
'fields': (('name', 'letter'), 'questions', 'color')
}),
)
π€shefHauwanga
15π
You can use this library
https://github.com/jaredly/django-colorfield
Installation:
- Run
pip install django-colorfield
- Add
colorfield
to yourINSTALLED_APPS
- Collect static files with
./manage.py collectstatic
Usage:
In your models, you can use it like this:
from django.db import models
from colorfield.fields import ColorField
class MyModel(model.Model):
color = ColorField(default='#FF0000')
- [Django]-Aggregate (and other annotated) fields in Django Rest Framework serializers
- [Django]-Django+Postgres: "current transaction is aborted, commands ignored until end of transaction block"
- [Django]-Django Admin β Overriding the widget of a custom form field
3π
If you want to add a color picker to a forms.Form
rather than a model.Model
this would be the way to go:
from django import forms
class GaeParamsForm(forms.Form):
hex_color = forms.CharField(label='hex_color', max_length=7,
widget=forms.TextInput(attrs={'type': 'color'}))
font_size = forms.IntegerField(label='font_size',
min_value=1, max_value=400)
This essentially writes the type attribute of the input HTML tag, i.e.
<input id="id_hex_color" maxlength="7" name="hex_color" type="color">
You will receive the data as hex string with # sign e.g. #ff0000
.
π€xjcl
- [Django]-Bad request 400: nginx / gunicorn
- [Django]-Embedding JSON objects in script tags
- [Django]-How to run Debug server for Django project in PyCharm Community Edition?
Source:stackexchange.com