Django博客编辑后重定向至文章页及NoReverseMatch问题解决
Ah, that NoReverseMatch error is a classic gotcha when working with Django's reverse function! Let's break down what's going wrong and fix it step by step.
The Core Issue
Your current code is passing the view_post function directly to reverse(), which isn't how the function works by default. reverse() expects either the name of your URL pattern (from urls.py) or a model's get_absolute_url() method—it doesn't accept view functions as the primary argument in most cases.
Step 1: Ensure Your URL Pattern Has a Name
First, check your urls.py and make sure you've assigned a name to your view_post route. This is how Django maps names to actual URLs:
# urls.py from django.urls import path from . import views urlpatterns = [ # ... other routes ... # Add the 'name' parameter to your view_post URL path('post/<int:post_id>/', views.view_post, name='view_post'), path('post/edit_post/<int:post_id>/', views.edit_post, name='edit_post'), ]
Step 2: Fix the Redirect in edit_post
Now update your edit_post view to use the URL name instead of the view function. Here's the corrected code:
# views.py from django.http import HttpResponseRedirect from django.urls import reverse from .models import Post def edit_post(request, post_id): post = Post.objects.get(id=post_id) if request.method == 'POST': # ... your form handling and save logic here ... post.save() # Use the URL name 'view_post' and pass the post_id as an argument return HttpResponseRedirect(reverse('view_post', args=[post_id])) # ... your GET request handling (render edit form) ...
Bonus: Use get_absolute_url (Django Best Practice)
For a cleaner, more maintainable approach, add a get_absolute_url method to your Post model. This lets you reference the post's detail page directly from the model instance:
# models.py from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() # ... other fields ... def get_absolute_url(self): # Returns the URL for this post's detail page return reverse('view_post', args=[self.id])
Then in your edit_post view, you can simplify the redirect to:
return HttpResponseRedirect(post.get_absolute_url())
Quick Checks to Rule Out Other Issues
- Double-check that
post_idis a valid integer corresponding to an existingPostobject. - Ensure your URL pattern for
view_postuses the same parameter name (post_id) as the one you're passing toreverse()(mismatched names will also causeNoReverseMatch).
内容的提问来源于stack exchange,提问作者pyknight202

