我正在嘗試設置我的網站,以便我的工作詳情的網址將使用slug字段而不是pk。它告訴我,它無法用給定的slu find找到我的工作(這是一個int,147)。Django使用Slug字段獲取詳細信息URL
更新:
在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')
爲什麼你的slug字段是int?這打破了一個slu whole的整個目的。還要注意,你的'get_object'和'get'方法都是毫無意義的,你應該刪除它們。 –
這是一個int,因爲我使用其他系統的ID作爲我的slu。。我有很好的理由這樣做。 2)我曾經在一點上用重寫這些方法來實現某些事情,並沒有注意事後沒有必要的重寫。我會刪除它們。 – DragonBobZ