Home > Enterprise >  get() got an unexpected keyword argument 'pk'
get() got an unexpected keyword argument 'pk'

Time:01-04

I am learning how to use django, and I am trying to make some class based views. In this case I have a model named Recurso and I want to get an specific one based on it's id (the primary key).

This is my view:

class Recurso(View):
    model = Recurso
    def get(self, request, recurso_id):
        recurso = get_object_or_404(Recurso, pk=recurso_id)
        etiquetas = recurso.tags.all()
        context = { 'recurso': recurso, 'lista_etiquetas': etiquetas }
        return render(request, 'recurso.html', context)

And this is it's respective url:

path('proveedor/recurso/<int:recurso_id>', Recurso.as_view(), name='recurso'),

This is the Model:

class Recurso(models.Model):
    nombre = models.CharField(max_length=50)
    tags = models.ManyToManyField(Etiqueta)
    proveedor = models.ForeignKey(Proveedor, on_delete=models.CASCADE)
    descripcion = models.CharField(max_length=2000, default='SOME STRING')

    def __str__(self):
        return self.nombre   " de "   self.proveedor.nombre

This is the traceback I get:`

Traceback (most recent call last):
  File "C:\Users\evaho\Envs\stem4Girls\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\evaho\Envs\stem4Girls\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\evaho\Envs\stem4Girls\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\evaho\Envs\stem4Girls\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\evaho\stem4Girls\appSTEM4GIRLS\views.py", line 32, in get
    recurso = get_object_or_404(Recurso, pk=recurso_id)
  File "C:\Users\evaho\Envs\stem4Girls\lib\site-packages\django\shortcuts.py", line 76, in get_object_or_404
    return queryset.get(*args, **kwargs)

Exception Type: TypeError at /proveedor/recurso/6
Exception Value: Recurso.get() got an unexpected keyword argument 'pk'

CodePudding user response:

By naming your view Recurso as well, it will use the view class, not the model class. You can fix this by renaming the view, for example to RecursoView:

class RecursoView(View):
    model = Recurso
    def get(self, request, recurso_id):
        recurso = get_object_or_404(Recurso, pk=recurso_id)
        etiquetas = recurso.tags.all()
        context = { 'recurso': recurso, 'lista_etiquetas': etiquetas }
        return render(request, 'recurso.html', context)

I would strongly advise to always use a …View suffix for your views to prevent clashes with models.

  •  Tags:  
  • Related