Is it possible to add 2nd slug to URL path in Django?

拥有回忆 提交于 2019-12-11 06:34:14

问题


I'm using Django version 2.1.

I want to create this type of URL Path in my Project: www.example.com/bachelor/germany/university-of-frankfurt/corporate-finance

Is it possible to do it in Django?


回答1:


Yes, say for example that you have a slug for an Author, and one for a Book, you can define it as:

# app/urls.py

from django.urls import path
from app.views import book_details

urlpatterns = [
    path('book/<slug:author_slug>/<slug:book_slug>/', book_details),
]

Then the view looks like:

# app/views.py

from django.http import HttpResponse

def book_details(request, author_slug, book_slug):
    # ...
    return HttpResponse()

The view thus takes two extra parameters author_slug (the slug for the author), and book_slug (the slug for the book).

If you thus query for /book/shakespeare/romeo-and-juliet, then author_slug will contains 'shakespeare', and book_slug will contain 'romeo-and-juliet'.

We can for example look up that specific book with:

def book_details(request, author_slug, book_slug):
    my_book = Book.objects.get(author__slug=author_slug, slug=book_slug)
    return HttpResponse()

Or in a DetailView, by overriding the get_object(..) method [Django-doc]:

class BookDetailView(DetailView):

    model = Book

    def get_object(self, queryset=None):
        super(BookDetailView, self).get_object(queryset=queryset)
        return qs.get(
            author__slug=self.kwargs['author_slug'],
            slug=self.kwargs['book_slug']
        )

or for all views (including the DetailView), by overriding the get_queryset method:

class BookDetailView(DetailView):

    model = Book

    def get_queryset(self):
        qs = super(BookDetailView, self).get_queryset()
        return qs.filter(
            author__slug=self.kwargs['author_slug'],
            slug=self.kwargs['book_slug']
        )


来源:https://stackoverflow.com/questions/52246161/is-it-possible-to-add-2nd-slug-to-url-path-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!