How to specify something other than pk or slug for DetailView

我与影子孤独终老i 提交于 2019-12-22 04:20:05

问题


I was wondering if it was possible to use something besides a pk or slug when you are using a DetailView in Django 1.3.

For example, I currently have:

url(r'^mymodel/(?P<pk>\d+)/$', MyDetailView.as_view())

as my url. Say I wanted something like:

url(r'^mymodel/(?P<name>\d+)/$', MyDetailView.as_view())

where name would be a field in the model. Is there anyway to have the DetailView use that to 'grab' the object I want and pass it on to my template?


回答1:


A slug doesn't have any particular significance in Django. It's just a name for a field that identifies a row. If your slug is called something else, eg name, just specify name as the slug_field attribute in your view subclass.

If you need something more complicated, you can always override get_object in the view class.




回答2:


You can use attribute "pk_url_kwarg"


urls.py

url(r'^mymodel/(?P<name>\d+)/$', MyDetailView.as_view())


views.py

class MyDetailView(LoginRequiredMixin, DetailView):
    model = ModelName
    pk_url_kwarg = "name" # primary key(to identify object uniquely)
    template_name = "template.html"

for reference view uml design http://epydoc.pythondiary.com/generic-views/ (click on detail view)



来源:https://stackoverflow.com/questions/5780803/how-to-specify-something-other-than-pk-or-slug-for-detailview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!