Lechucico
Lechucico

Reputation: 2102

Django custom ChoiceField form with selected=selected

I have the following form:

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

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

Here is the model that uses that positions:

class User(models.Model):
    id = models.CharField(max_length=10, primary_key=True)
    position = models.CharField(max_length=1, choices=POSSIBLE_POSITIONS, default=1)

And this is the view:

def modify(request):
    return render(request, 'interface/modify.html', {'user': User.objects.get(pk=id), 'device_list': Device.objects.all(), 'form': PositionForm()})

I would like to know, how to select the default Position based on the current user.position.

Just like I do here:

<select name="device_id" class="form-control">
   {% for device in device_list %}
      {% if device.id == user.device.id %}
         <option selected="selected">{{ device.id }}</option>
      {% else %}
         <option>{{ device.id }}</option>
      {% endif %}
   {% endfor %}
   {% if user.device.id == None %}
      <option selected="selected"> Sin dispositivo </option>
   {% else %}
      <option> Sin dispositivo </option>
   {% endif %}
</select>

But I don't know how to do it here:

<div class="form-group">
   <label>Posición actual dispositivo</label>
   {{ form }}
</div>

Upvotes: 0

Views: 1639

Answers (2)

Kres
Kres

Reputation: 154

If I understand your question correctly you should do the following modification in your view:

def modify(request):
    user = User.objects.get(pk=id)
    form = PositionForm(initial={'position': user.position})
    return render(request, 'interface/modify.html', {'user': user, 'device_list': Device.objects.all(), 'form': form})

Upvotes: 1

LeLouch
LeLouch

Reputation: 611

you can select any option by manually doing that in regular html like that

<select name="device_id" class="form-control">
            <option value="1"> Brazo</option>
            <option value="2"> Muñeca</option>
            <option value="3" selected> Pierna</option>
            <option value="4"> Pie </option>
            
</select>

so you can just add this if statment in your option tag

`<option {% if user.position %} selected {% endif %}>` 

and the selected one will be the default one

Upvotes: 0

Related Questions