I'm writhing an app with class based views. I need to receive 'pk' in my views.py file when I load my page using generic DetailView.
My urls.py file:
from django.urls import path
from . views import HomeView, ProfileView, AddPetView, EditPetView, DeletePetView,
PetProfileView
urlpatterns = [
...
path('profile/pet/<int:pk>', PetProfileView.as_view(), name='pet_profile'),
path('', HomeView.as_view(), name='home'),
]
My views.py file:
from django.shortcuts import render
from django.views.generic import TemplateView, ListView, UpdateView, CreateView, DeleteView,
DetailView
from django.urls import reverse_lazy
from . models import Pet
class PetProfileView(DetailView):
model = Pet
template_name = 'pet_profile.html'
#key = Pet.objects.values_list('birth_date').get(pk=1)
I need to extract from database birh_date column for this specific pet. How to get this pk=? when I load pet_profile page?
I'm not sure if I can describe the case well. If something is not clear, ask me. I will try to explain again.
CodePudding user response:
On class based views:
self.kwargs['pk']
So, in your case
class PetProfileView(DetailView):
model = Pet
template_name = 'pet_profile.html'
def get_key(self):
Pet.objects.values_list('birth_date').get(pk=self.kwargs['pk'])
You can access to your key inside the class with this function:
key = self.get_key()
CodePudding user response:
As already mentioned you can access the URL parameters like self.kwargs["pk"]
. But as you are already using a DetailView
which already provides the functionality to retrieve an object via its id you can customize the queryset it uses:
class PetProfileView(DetailView):
model = Pet
template_name = 'pet_profile.html'
queryset = Pet.objects.values_list('birth_date')
(Though without doing this you should also be able to access pet.birth_date
in your template)