Ray Tango
Ray Tango

Reputation: 107

Django forms and Material Design Lite

I'm building my frontend with Google's MDL framework and I'm having troubles rendering Django forms with MDL's styling using:

{{ form.as_table }}
{{ form.as_p}}
{{ form.as_ul}}

Tried this way also:

    <form>
        <div class="mdl-textfield mdl-js-textfield">
            {% for field in form %}
            <label class="mdl-textfield__label" for="{{ field.name }}">{{ field.label_tag }}</label>
            {{ field }}
            {% endfor %}
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>

My Django form class:

class MyClassUpdateForm(forms.ModelForm):
    class Meta:
        model = MyClass
        fields = '__all__'
        widgets = {
            'foo': TextInput(attrs={'class': "mdl-textfield__input"}),
            'bar': TextInput(attrs={'class': "mdl-textfield__input"}),
            'baz': TextInput(attrs={'class': "mdl-textfield__input"}),
        }

I'm trying to use this block of code from MDL's components:

<form action="#">
  <div class="mdl-textfield mdl-js-textfield">
    <input class="mdl-textfield__input" type="text" id="sample1">
    <label class="mdl-textfield__label" for="sample1">Text...</label>
  </div>
</form>

Upvotes: 3

Views: 1482

Answers (1)

Rishabh Nehra
Rishabh Nehra

Reputation: 11

This is how I've done in my project. Assuming that you have a model form named a 'form', which has a 'foo' attribute, then:-

<form method="POST">
    <input class="mdl-textfield__input" type="text" id="id_{{ form.foo.name }}" name="{{ form.foo.name }}" value="{% if form.foo.value != None %}{{ form.foo.value }}{% endif %}" required>
    <label class="mdl-textfield__label" for="id_{{ form.foo.name }}">Text...</label>
</form>

Upvotes: 1

Related Questions