Django Choices Object Not passing id to URL

864 views Asked by At

I'm using a model with a choices field that is being displayed by a form. I want to create a delete function in my views.py but can't get it to work. I suspect it's because my model object is not passing an id, or my url just isn't picking the object's id for whatever reason.

Here's my model.

class Player(models.Model):

    PLAYER_ROLE_CHOICES = (
        (1, 'Quarterback'),
        (2, 'Runningback'),
        (4, 'Widereceiver'),
        (5, 'Tightend'),
        (6, 'Kicker'),
        
    )
    role = models.PositiveSmallIntegerField(choices=PLAYER_ROLE_CHOICES)

Here's the delete function I'm trying to make in views.py

def delete_player(request, id):
    player = Player.objects.get(id=id)
    player.delete()
    
    
    return redirect('show')

and my url

path('delete_player/<int:id>', views.delete_player, name="delete_player")

Here''s the relevant line from my template.

<tr>  
        
        <td>{{ QB }}  
             
            <a href="{% url 'game:delete_player' player.id %}">Delete</a>  
        </td> 
        
    </tr> 

I know that I obviously need an id to be passed to both the url and delete function in views.py, but I don't know how to get the id from my model. I'd appreciate any help/another set of eyes on the problem. Thanks in advance.

1

There are 1 answers

3
Masud Dipu On

Suppose you have an object of Player in django template. Using relative url 'delete_player' you can easily create an anchor tag to call Player delete view.

So simply you can write:

<a href="{% url 'delete_player' object.id %}">Delete</a>

for more info you can visit official documentation