You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django搜索结果跳转路径错误问题求助

Hey there, let's get to the bottom of why your search results are redirecting to the wrong URL path. The core problem here is relative vs absolute URL paths in your search template. Here's how to fix it step by step:

1. Understand the Root Cause

When you click a link in your search.html template, if you're using a relative path (like blogpost/{{ post.slug }}), the browser will append that path to your current page's URL. Since your search page is at /blog/search/, it becomes /blog/search/blogpost/my_article instead of the desired /blog/blogpost/my_article.

The best practice in Django is to use the {% url %} template tag to generate URLs dynamically—this avoids hardcoding paths and prevents breaks if you ever update your URL configurations later.

Step 2.1: Ensure Your Blogpost URL Has a Name

First, make sure your blogpost view has a named URL in your app's urls.py:

# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("search/", views.search, name="search"),
    # Add the name parameter to your blogpost path
    path("blogpost/<slug:slug>/", views.blogpost, name="blogpost"),
]

Replace your existing link in search.html with the {% url %} tag. For example:

<!-- Before (relative path - causes the issue) -->
<a href="blogpost/{{ post.slug }}">{{ post.title }}</a>

<!-- After (dynamic absolute path - fixes the issue) -->
<a href="{% url 'blogpost' slug=post.slug %}">{{ post.title }}</a>

If you prefer not to use the {% url %} tag (not recommended for maintainability), you can use an absolute path starting with /:

<a href="/blog/blogpost/{{ post.slug }}">{{ post.title }}</a>

3. Verify Your Project's URL Configuration

Double-check that your project's main urls.py includes your blog app's URLs correctly:

# project/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),  # This ensures /blog/ prefix is applied
]

That's it! Your search result links should now redirect directly to /blog/blogpost/my_article as expected.

内容的提问来源于stack exchange,提问作者KhAliq KHan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:57:13