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.
2. Fix the Link in Your Template
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"), ]
Step 2.2 Update the Link in search.html
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

