Guillermo Vázquez
Guillermo Vázquez

Reputation: 159

What can I do to make 'id' = id in this class-based view in Django?

views.py

from django.shortcuts import render
from django.views.generic import DetailView
from .models import Producto


def general_view(request):
    context = {
        'articulos': Producto.objects.all(),
    }
    return render(request, 'shop/general_view.html', context)


class DetailedView(DetailView):
    model = Producto
    template_name = 'shop/specific_view.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['determinado'] = Producto.objects.get(pk=*¿?*)
        return context

urls.py

from django.urls import path
from . import views
from .views import DetailedView

urlpatterns = [
    path('', views.general_view, name='general-view'),
    path('<int:pk>/', DetailedView.as_view(), name='specific-article'),
]

As you see, the problem occurs because I don't know how to call the id or pk in the detailed_view in views.py, I'm guessing you maybe have to do a dictionary but I don't know where to do it nor how. It works if I set the id to 1, but obviously what this does is that is shows in every url with a different id the same article.

Upvotes: 1

Views: 630

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477686

You do not need to do that yourself. The idea is that the DetailView has the boilerplate code, to automatically filter on the primary key. You can simply set the .context_object_name attribute [Django-doc] to 'determinado':

class DetailedView(DetailView):
    model = Producto
    template_name = 'shop/specific_view.html'
    context_object_name = 'determinado'

    # no override of get_context_data

Upvotes: 1

Related Questions