I have a model
# models.py
from django.db import models
class Foo(models.Model):
# ...
color = models.CharField(max_length=7, null=True)
color
should store a hex-color. Instead of a input type="text"
I would like to use the html5 input type "color".
I tried this by setting up the following form object:
# forms.py
from django.forms import ModelForm, CharField
class FooForm(ModelForm):
class Meta:
model = Foo
widgets = {
'color': CharField(attrs={'type': 'color'}),
}
However, this gives me the following error message
init() got an unexpected keyword argument 'attrs'
What am I doing wrong and how would I do it right?
Solved it myself. It works nearly like I expected:
# models.py
from django.db import models
class Foo(models.Model):
# ...
color = models.CharField(max_length=7, null=True)
# forms.py
from django.forms import ModelForm
from django.forms.widgets import TextInput
class FooForm(ModelForm):
class Meta:
model = Foo
widgets = {
'color': TextInput(attrs={'type': 'color'}),
}
The part that was tricky for me was not to forget to set it up right in the view:
# views.py
from my_app.models import Foo
from my_app.forms import FooForm
class FooCreate(CreateView):
model = Foo
form_class = FooForm
Thanks to aamir-adnan - he pointed out that I have to use TextInput instead of CharField.
If you just need to update the type
attr, you need to update the widget attrs which is a TextInput for CharField:
class FooForm(ModelForm):
def __init__(self, *args, **kw):
super(FooForm, self).__init__(*args, **kw)
self.fields['color'].widget.attrs.update({
'type': 'color',
})
class Meta:
model = Foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With