[英]Dynamic URL routing for a class-based view
我想將函數視圖轉換為基於類的視圖。
這是我現在擁有的視圖和 URL 路徑。
看法:
def customer(request, pk):
customer = Customer.objects.get(id=pk)
return render(request, 'accounts/customer.html)
網址路徑:
path('customer/<str:pk>/, views.customer, name='customer')
將此視圖轉換為基於類的視圖的正確語法是什么。 我主要是好奇如何使用基於類的視圖訪問這里的主鍵。
謝謝!
您可以使用詳細信息視圖。
在你的 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
在 urls.py 中
path('customer/<int:pk>', views.CustomerDetails.as_view(), name='customer')
將傳遞給 customerdetail.html 模板的上下文將具有默認名稱“對象”。 通過 {{object.<field_name>}} 訪問客戶實例的字段。 您可以覆蓋 DetailView 的屬性和方法。
更多信息: DetailView
如果您想在視圖中進行更多控制,可以使用通用視圖
from django.views.generic.detail import View
from .models import Customer
class CustomerDetails(View):
def get(self, *args, **kwargs):
customer = Customer.objects.get(id=kwargs['pk'])
return render(self.request, 'accounts/customer.html)
網址.py
path('customer/<int:pk>', views.CustomerDetails.as_view(), name='customer')
在 url 中找到的參數存儲在**kwargs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.