How to specify something other than pk or slug for DetailView
Asked Answered
F

2

9

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?

Fredericafrederich answered 25/4, 2011 at 17:2 Comment(0)
E
14

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.

Ectophyte answered 25/4, 2011 at 17:30 Comment(3)
Overriding is all I needed to do here. Thanks!Fredericafrederich
also note that your url line must look like: url(r'^mymodel/(?P<slug>\d+)/$', MyDetailView.as_view())Mandrake
You can set slug_url_kwarg in addition to slug_field so that your named parameter is not "slug" as user mpaf suggested.Hercule
M
1

You can use attribute "pk_url_kwarg"

urls.py

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

views.py

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

Reference: https://ccbv.co.uk/projects/Django/4.1/django.views.generic.detail/DetailView/

Mediatorial answered 29/6, 2016 at 6:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.