我正在尝试设置我的网站,以便我的工作细节的网址将使用slug字段而不是pk。它告诉我它找不到给定的slug(这是一个int,147)我的工作。
在https://ccbv.co.uk/projects/Django/1.11/django.views.generic.detail/DetailView/查看DetailView说明后,我意识到slug_field
有一个DetailView
属性。我的新观点如下:
class JobDetailView(CacheMixin, DetailView):
model = Job
slug_field = 'slug'
网址:
urlpatterns = [
url(r'^careers$', views.job_list, name='job-list'),
url(r'^careers/(?P<slug>[0-9]+)/$', views.JobDetailView.as_view(), name='job-detail'),
]
视图:
class JobDetailView(CacheMixin, DetailView):
model = Job
pk_url_kwarg = 'slug'
def get_object(self, *args, **kwargs):
# Call the superclass
object = super(JobDetailView, self).get_object()
# Return the object
return object
def get(self, request, *args, **kwargs):
object = super(JobDetailView, self).get(request, *args, **kwargs)
return object
模型:
class Job(UpdateAble, PublishAble, models.Model):
slug = models.CharField(unique=True, max_length=25)
facility = models.ForeignKey('Facility')
recruiter = models.ForeignKey('Recruiter')
title = models.TextField()
practice_description = models.TextField(blank=True, default="")
public_description = models.TextField(blank=True, default="")
objects = JobManager()
def get_next(self, **kwargs):
jobs = Job.objects.published()
next = next_in_order(self, qs=jobs)
if not next:
next = jobs[0]
return next
def get_prev(self, **kwargs):
jobs = Job.objects.published()
prev = prev_in_order(self, qs=jobs)
if not prev:
prev = jobs[len(jobs)-1]
return prev
def __str__(self):
return f'{self.facility}; {self.title}'
管理器:
class JobManager(models.Manager):
def published(self):
return super(JobManager, self).get_queryset().filter(is_published=True).order_by('facility__name', 'title')
答案 0 :(得分:2)
你实际上根本不需要定义pk_url_kwarg
,事实上你这样做会让你感到困惑,导致找不到对象。
从the default implementation of get_object
可以看到,该视图通常会在网址中查找pk
或slug
kwarg;找到的任何一个都将用于查找。但是,通过将pk_url_kwarg
设置为slug
,您可以告诉视图获取名为&#34; slug&#34;的URL kwarg。但是使用它来查看PK字段,这显然不会起作用。
完全删除该属性,Django将检测你的slug kwarg并使用它来正确查看slug字段。