简体   繁体   中英

Django: DetailView - pk or a slug

Old views.py

from django.views.generic.detail import DetailView
...
def foo:
  ...
  return object_detail(request, queryset, id, template_object_name = 'group')

New views.py

class TestDetailView(DetailView):
    def get_context_data(self, **kwargs):
        context = super(TestDetailView, self).get_context_data(**kwargs)
        return context

def foo:
  ...
  return TestDetailView.as_view(queryset = queryset, context_object_name = 'group')(request)

Error: eneric detail view TestDetailView must be called with either an object pk or a slug.

Question: tell me please, how am I supposed to pass id in the new views.py ?

It seems that the raight decision is to overwrite get_object , smth like this:

def get_object(self):
        return get_object_or_404(TestGroup, id = id)

I've also tried this solution:

return TestDetailView.as_view(queryset = queryset, context_object_name = 'group')(request, pk = id)

But then I've got Reverse for 'foo.views.testgroup_edit' with arguments '(u'group.id',)' and keyword arguments '{}' not found.

Where I call it like this:

{% url 'foo.views.testgroup_report_builder' group.id %}

You don't use class-based views like this. They are classes. You should get rid of your foo function altogether and just reference TestDetailView from the urls.py. If you need to do some extra custom logic in your view which is currently in foo, then subclass TestDetailView and do it there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM