Django 2 pick up parameter passed in the url inside a ListView

0

If I have a URL that passes a parameter as follows

http://mysite/person/car?parametro=1

In a ListView I get that parameter in the following way

Parametro = request.GET.get("id")

But if the parameter is passed in the url

"person/<int:parametro>/car/"

For example, it would appear in the browser

 http://mysite/person/1/car

How do I pick up the parameter within the ListView?

At the moment I have managed to work as follows

class MiVista(ListView):
    Model = Mimodelo
    template_name ='mitemplate.html'

    #recoger la variable para filtrar según su valor
    def get_queryset(self, **kwargs):
        #obtengo el parametro 
        parametro = self.kwargs.get('parametro',None)
        #filtro mi modelo según el parametro
        queryset = Mimodelo.objects.filter(id=parametro) 

    # agregamos al contexto el parametro para poder hacer en el
    # template {{parametro}}  
    def get_context_data(self, **kwargs):
         #obtengo el contexto actual
        context=super(MiVistam, self).get_context_data(**kwargs)
         # recojo el parametro 
        parametro = self.kwargs.get('parametro', None) 
         #agrego parametro al diccionario de contexto
        context['parametro'] = parametro            
        return context

This works in a view, but. Is there a simpler way to do it?

    
asked by user1640529 10.07.2018 в 20:09
source

1 answer

0

If you already have the URL as you describe it "person // car /"

The way to capture the parameter would be:

def nombre_de_la_vista(request, parametro):
    return True

Remember that if you change the name in the url you have to change it in the view too.

    
answered by 10.07.2018 в 20:47