1

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

2 Answers 2

1

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'
Sign up to request clarification or add additional context in comments.

2 Comments

This has to be placed on the PositionForm Class, no? It throws a key error with 'name'.
You should set it for position
0

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'
        }
    ))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.