Skip to content Skip to sidebar Skip to footer

Django Templates And Drop-down List

I would like to render a Django form in the following manner... Form UI In particular, how would I go about populating and rendering the three drop-down lists based on the model pr

Solution 1:

Since your question was only directed to form rendering . . .

In the view:

class DefaultSquadsViewCreate(CreateView):
    template_name = 'fafl/defaultSquad_form.html'
    model = DefaultSquads
    fields = ['player', 'position_code', 'playing_status_code']
    success_url = reverse_lazy('fafl:defaultSquads-list')

    def get_context_data(self, **kwargs):
        context = super(DefaultSquadsView, self).get_context_data(**kwargs)
        context['clubs'] = Clubs.objects.all().order_by('club_id')
        context['players'] = Players.objects.all().order_by('player_id')
        context['positions'] = Positions.objects.all()
        return context

In the template:

<divclass="form-group"><labelfor="{{ form.club.id_for_label }}"class="col-sm-2 control-label">Club</label><divclass="col-sm-10"><selectid="{{ form.club.id_for_label }}"name="{{ form.club.html_name }}"class="form-control"><optionvalue=""selected>None</option>
          {% for club in clubs %}
          <optionvalue="{{ club.club_id }}">{{ club.nickname }}</option>
          {% endfor %}
        </select></div></div><divclass="form-group"><labelfor="{{ form.player.id_for_label }}"class="col-sm-2 control-label">Player</label><divclass="col-sm-10"><selectid="{{ form.player.id_for_label }}"name="{{ form.player.html_name }}"class="form-control"><optionvalue=""selected>Please select a player</option>
          {% for player in players %}
          <optionvalue="{{ player.player_id }}">{{ player.display_name }}</option>
          {% endfor %}
        </select></div></div><divclass="form-group"><labelfor="{{ form.postion_code.id_for_label }}"class="col-sm-2 control-label">Position Code</label><divclass="col-sm-10"><selectid="{{ form.position_code.id_for_label }}"name="{{ form.position_code.html_name }}"class="form-control"><optionvalue=""selected>Please select a Position</option>
          {% for position in positions %}
          <optionvalue="{{ position.position_code }}">{{ position.name }}</option>
          {% endfor %}
        </select></div></div>

Post a Comment for "Django Templates And Drop-down List"