Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using html5 input type='color'

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?

like image 625
speendo Avatar asked Mar 13 '14 22:03

speendo


2 Answers

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.

like image 148
speendo Avatar answered Sep 29 '22 19:09

speendo


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
like image 26
Aamir Rind Avatar answered Sep 29 '22 21:09

Aamir Rind