Search code examples
pythondjangourl-routing

Dynamic URL routing for a class-based view


I want to turn a function view into a class-based view.

Here is the View & URL path that I have right now.

View:

def customer(request, pk):
    customer = Customer.objects.get(id=pk)
    return render(request, 'accounts/customer.html)

URL Path:

path('customer/<str:pk>/, views.customer, name='customer')

What would the proper syntax be to turn this view into a class-based view. I am mainly curious about how to access the primary key here using a class-based view.

Thanks!


Solution

  • You can use Detail View.

    in your views.py

    from django.views.generic.detail import DetailView
    from .models import Customer
    
    class CustomerDetails(DetailView):
        model = Customer 
        template_name = 'customerdetail.html'   #deafaults to customer_detail.html
    

    in urls.py

    path('customer/<int:pk>', views.CustomerDetails.as_view(), name='customer')
    

    the context that will be passed to customerdetail.html template will have the default name 'object'. access the fields of customer instance by {{object.<field_name>}}. You can override the attributes and methods of DetailView.

    for moreinfo : DetailView