python - 在 DetailView 中使用对象
问题描述
假设我有一个名为 City 的模型,它有一个 name 属性。在我的 DetailView 中,我想使用单击它的特定城市的名称来发出一些 api 请求,然后将其发送到 detailview.html。
有没有办法访问它?
解决方案
如果 的name
是City
唯一的,是的。例如,您可以创建一个 URL:
from django.urls import path
from app_name.views import CityDetailView
urlpatterns = [
path('city/<str:name>/', CityDetailView.as_view(), name='city-detail'),
]
然后你可以做一个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'])
在模板中,例如列出城市的模板,您可以生成一个 URL:
<a href="{% url 'city-detail' 'Bucharest' %}">Bucharest</a>
然而,通常不使用名称,而是使用slug [Django-doc]。蛞蝓通常在视觉上更令人愉悦,因为它避免了百分比编码数据。通常,您还会在 slug 字段上添加数据库索引。此外,aDetailView
会查看 url 是否有一个名为 slug 的参数,然后会自动尝试过滤模型中名为 slug 的字段。
推荐阅读
- c - 使用函数或指向函数符号的指针之间有什么区别吗?
- django - 未选择单选按钮时选择警告
- python-3.x - pyomo 列出可用的求解器
- ios - 来自 URL 的 UIImage 需要太多时间才能出现
- python - How does pytorch broadcasting work?
- r - 如何将新数据映射/绘制到训练有素的 SOM 地图上?
- c++ - Difference between 'new' and '=' in relation to pointers
- git - git worktree update remote branch
- android - 用于开发使用视频流的应用程序的 Windows 或 Android 平板电脑
- java - exec-maven-plugin 跳过多个条件