简体   繁体   中英

django use slug not pk

I'm trying to use slug in my url, I've done this fine on other sites but for some reason, I am unable to use slug in a url on this area of the site, only the primary key gets the desired result, what am i missing here? The only difference from the other sites I have done is that the slug will be used for filtering which is what I think is messing this up.

Model:

class Desk(models.Model):
    name = models.CharField(max_length=16, unique=True)
    slug = models.SlugField(max_length=16, unique=True)

    def __str__(self):
        return self.slug


class Handover(models.Model):
    desk = models.ForeignKey(
        Desk,
        related_name="handover",
        on_delete=models.CASCADE
    )
    published = models.DateTimeField(auto_now_add=True)
    user = models.CharField(max_length=45)
    ongoing = models.CharField(max_length=1024, null=True, blank=True)
    resolved = models.CharField(max_length=1024, null=True, blank=True)
    planned_work = models.CharField(max_length=1024, null=True, blank=True)
    heightened_awareness = models.CharField(max_length=1024, null=True, blank=True)

In the views below, for some reason I can't use the word 'slug' in the filter, it just throws an error. The current setup works if I use the PK in the url in the browser, but not the slug which is what I want to use, (I'm not sure why this works either, I would expect this not to work because of using 'slug' in the url).

Here is the view:

class IndexView(ListView):
    template_name = 'pcc_homepage/index.html'
    queryset = Handover.objects.order_by('-published')

    def get_queryset(self):
        return Handover.objects.filter(desk=self.kwargs['desk'])

Here is the urls:

urlpatterns = [
    path('home/<slug:slug>/', IndexView.as_view(), name='index'),
    path('handover/', HandoverCreateView.as_view(), name='handover'),
]

How can I make this work with a human readable word and not an integer please.

你可以试试 Handover.objects.filter(desk__slug=self.kwargs['desk'])

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