简体   繁体   中英

Django template fetching value from option tag

I want to fetch selected option value, and then display content dependent of chosen option

template

<div class="match-wrapper">    
  <select name="team">
    {%for team in teams%}            
       <option class='option-select' value="{{team}}">{{team}}</option>
    {%endfor%}
  </select>
  {%for player in players%}
    <div data-team="AGO K1CK DV1 PIRATESPORTS IHG DC PRIDE AVEZ">
        <span>{{player}}</span>
    </div>
  {%endfor%}
</div>

views.py

def profile(request):
    players = {'AGO':['Szygenda', 'Zanzarah', 'Czekolad', 'Woolite', 'Mystqiues'], 'K1CK':['Ibo', 'Shlatan', 'Matislaw', 'Puki Style', 'Raxxo'],
        'DV1':['Sinmivak', 'Bruness', 'Czajek', 'Bullet', 'Pyrka'], 'Piratesports':['Konvektiv', 'Behave', 'Roison', 'Defles', 'Sedrion'],
        'IHG':['Melonik', 'Kikis', 'Niq', 'Unforgiven', 'Jesiz'], 'Pride':['Rifty', 'Raxhy', 'Warszi', 'KMŚ'], 'DC':['Unknown', 'Crazy', 'Fresskowy', 'Itrzrenifer', 'Blue45ty'],'Avez':['Czaru', 'Bolszak', 'Bucu', 'Trenie','Kubyd']
    }
    teams = ['AGO', 'K1CK', 'DV1', 'PIRATESPORTS', 'IHG', 'DC', 'PRIDE', 'AVEZ']

    context = {
        'teams':teams,
        'players':players['AGO'],

    }
    return render(request, 'profilecontent/profile.html', context)

It looks like you want to change what content is shown if condition, based on the selected option in the for loop? That isn't something you can do just with Django templates, you need to either either use a form to submit the value of the <select> , or use JavaScript.

For the form approach you could follow the Django Working with forms guide, it gives a good overview of how it all works. This approach will also allow you to use the data in other ways too, eg saving the chosen option for future visits.

The JavaScript approach can be good if you don't want to reload the page before seeing changes. Here's a simple example of how it could work.

<div class="match-wrapper">
  <select name="team">
    {% for team in teams %}
      <option class="option-select" value="{{ team }}">{{ team }}</option>
    {% endfor %}
  </select>

  <div data-team="AGO">
    <span>AGO</span>
  </div>
  <div data-team="K1CK DV1 PIRATESPORTS IHG DC PRIDE AVEZ">
    <span>Not AGO</span>
  </div>
</div>

<script>
  const select = document.querySelector('select[name="team"]');

  select.addEventListener('input', (event) => {
    const targets = document.querySelectorAll('[data-team]');
    for (const target of targets) {
      const teams = target.dataset.team.split(' ');
      target.hidden = !teams.includes(select.value);
    }
  });

  select.dispatchEvent(new Event('input'));
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM