Django URL调度器-尝试下一个视图

voj3qocg  于 2023-01-31  发布在  Go
关注(0)|答案(2)|浏览(160)

好吧,我给你们举个例子
我们在Django中有以下url配置。
Django会尝试用下面的规则来匹配url,一旦找到匹配项,它会使用合适的视图并在模型中查找对象。
问题是,一旦它在URL模式中找到匹配项,它就会匹配视图,但是一旦视图中的对象找不到,它就会返回一个页面未找到(404)错误。

www.example.comurls.py

from django.urls import path

from . import views

urlpatterns = [
    path('articles/<slug:category>/<slug:editor>/', views.ArticleByThemeView.as_view(), name='articles_by_editor'),
    path('articles/<slug:category>/<slug:theme>/', views.ArticleDetailView.as_view(), name='articles_by_theme')
]

www.example.comviews.py

class ArticleByThemeView(ListView):
    """
    List all articles by a certain theme; "World War 2".
    """
    model = Article
    
    def dispatch(self, request, *args, **kwargs):
        try:
            # Check if the theme_slug matches a theme
            theme = ArticleTheme.objects.get(slug=self.kwargs['theme_slug'])
        except ArticleTheme.DoesNotExist:
            # Theme does not exist, slug must be an article_slug
            return redirect(
                'article_detail',
                category_slug=category_slug
                article_slug=theme_slug
            )
        return super().dispatch(request, *args, **kwargs)

class ArticleDetailView(DetailView):
    """
    Detailview for a certain article
    """
    model = Article

    def get_object(self):
        return get_object_or_404(
            Article,
            category__slug=self.kwargs['category_slug'],
            slug=self.kwargs['article_slug']
        )

我们有以下的网址模式,我们可以按编辑或按主题排序文章。我们这样做是为了创建一个符合SEO目的的网址结构。
一旦找不到对象,我们有没有办法重定向到另一个视图?
我们可以修改分派方法以返回到url模式并找到以下匹配规则吗?

kdfy810k

kdfy810k1#

像这样的重定向怎么样:

def articles_by_editor(request, category, editor):
    try:
        article = Article.objects.get(category=category, editor=editor)
        # return article
    except Article.DoesNotExist:
        # redirect to another view
        return redirect('articles_by_theme', category=category)
mwg9r5ms

mwg9r5ms2#

好吧,
根据Sunderam Dubey的建议,我编写了一个函数视图,它使用两种不同的路径访问同一个视图。

www.example.comurls.py

from django.urls import path

from . import views

urlpatterns = [
    path('articles/<slug:category>/<slug:slug>/', views.article_theme_or_detail_view, name='article_by_theme'),
    path('articles/<slug:category>/<slug:slug>/', views.article_theme_or_detail_view, name='article_detail')

]

www.example.comviews.py

def article_theme_or_detail_view(
    request,
    category_slug,
    slug=None
):
    """
    This view could either be for a theme view or detailview,
    depending on the slug.
    """
    try:
        # Check if the slug represents a theme
        theme = ArticleTheme.objects.get(slug=slug)
        article_list = Article.object.filter(theme=theme)
        
        # Add context
        context = {
            'theme': theme,
            'article_list': article_list
        }

        # Render the template with context
        return render(
            request,
            'article_by_theme.html',
            context
        )
    except ArticleTheme.DoesNotExists:
        # The theme does not exist so the slug must be for a detail view
        context = {
            article = Article.objects.get(slug=slug)
        }

        return render(
            request,
            'article_detail.html',
            context
        )

待办事项:

  • 删除其中一个url路由

相关问题