Home > database >  How to get value of select form inside the views?
How to get value of select form inside the views?

Time:07-13

  1. In the HTML template I created a select form passing into it player names from Player Model.
  2. I want to delete the player selected in this form.
  3. Inside my views, I am trying to get the selected value as a string but I can't. for me it would be Player.objects.get(name="what is selected inside the form").

Can you please help? What should I do in order to get this value inside my views?

<div>
    <form method="POST" action = "" enctype="multipart/form-data">

        {% csrf_token %}

        <select name="to_delete" >
            {% for pl in players %}
            <option value="1">{{pl.name}}</option>
            {% endfor %}
        </select>


        <input type="submit" value="Delete"/>
    </form>

</div>

def deletePlayer(request,pk,sk):
    room = Room.objects.get(number=pk)
    player = Player.objects.get(number=sk)
    players = Player.objects.filter(room=room)
    if request.method == "POST":
        result = reguest.get('1')
        to_delete = Player.objects.get(name=result)
        to_delete.delete()


    context = {'room': room, 'players':players,'player':player}
    return render(request, 'base/delete_player.html', context)

CodePudding user response:

Your form is sending the data using POST method. To delete the data with their names, change the value of options in select with their names as well like this

<option value="{{pl.name}}">{{pl.name}}</option>

Then inside your views.py

result = request.POST.get('to_delete')

then use result to delete it from your table.

  • Related