Lechucico
Lechucico

Reputation: 2102

Django form using bootstrap

I have the following dictionary:

POSSIBLE_POSITIONS = (
    ('1', 'Brazo'),
    ('2', 'Muñeca'),
    ('3', 'Pierna'),
    ('4', 'Pie'),
)

This is used in the following form:

from interface.positions import *
from django import forms

class PositionForm(forms.Form):
    position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select())

This is the view that renders my html template:

def add(request):
    return render(request, 'interface/add_user.html', {'device_list': Device.objects.all(), 'form': PositionForm()})

And this is the html code:

<body>
    <form class="square" action="{% url 'interface:add_perform' %}" method="post">
        {% csrf_token %}
        <div class="form-group">
            <label>ID paciente</label>
            <input autofocus class="form-control" name="user_id" placeholder="Ejemplo: 58192">
        </div>
        <div class="form-group">
            <label>Dispositivo a usar</label>
            <select name="device_id" class="form-control">
                {% for device in device_list %}
                    <option>{{ device.id }}</option>
                {% endfor %}
                <option selected="selected"> Sin dispositivo </option>
            </select>
        </div>
        <div class="form-group">
            <label>Posición dispositivo</label>
            <div class="form-control"> {{ form }} </div>
        </div>
        <div class="form-group square_button">
            <button class="btn btn-success btn-md form-control" type="submit"> Crear Paciente </button>
        </div>
    </form>
</body>

The problem is that as you can see on the following image, this isn't bootstrap css, so it is really weird. How I can fix that?

I want it like the 'Dispositivo a usar' selector.

enter image description here

SOLVED

I found the solution here: Define css class in django Forms

Upvotes: 1

Views: 2045

Answers (2)

Bhavani Ravi
Bhavani Ravi

Reputation: 2291

Loop through form object and set the form-control class in select tag. It should work.

def __init__(self, *args, **kwargs):
    super(PositionForm, self).__init__(*args, **kwargs)
    self.fields['position'].widget.attrs['class'] = 'form-control'

Upvotes: 1

Lechucico
Lechucico

Reputation: 2102

Can be solved adding the css class directly on the form:

class PositionForm(forms.Form):
    position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select(
        attrs={
            'class': 'form-control'
        }
    ))

Upvotes: 0

Related Questions