Lets say i have a model named City, which has a name attribute. In my DetailView i want to use that name of the specific city it was clicked on to make some api requests and then send it to the detailview.html.
Is there a way to access it?
If the name
of the City
is unique, yes. You can for example make a URL:
from django.urls import path
from app_name.views import CityDetailView
urlpatterns = [
path('city/<str:name>/', CityDetailView.as_view(), name='city-detail'),
]
then you can make a DetailView
:
from django.shortcuts import get_object_or_404
from django.views.generic.detail import DetailView
from app_name.models import City
class CityDetailView(DetailView):
model = City
template_name = 'name_of_template.html'
def get_object(self, *args, **kwargs):
return get_object_or_404(City, name=self.kwargs['name'])
In a template, for example a template that lists cities, you can then generate a URL:
<a href="{% url 'city-detail' 'Bucharest' %}">Bucharest</a>
often however, one does not use the name, but a slug [Django-doc]. A slug is often more visually pleasant, since it avoids percent-ecoding data. Normally you also add a database index on a slug field. Furthermore a DetailView
will look if the url has a parameter named slug, and then automatically will try to filter on a field in the model named slug.