PostDetailView
和 PostCreateView
是 Django 框架中基于类的视图(Class-Based Views, CBVs)的两种常见用法。PostDetailView
通常用于展示单个帖子的详细信息,而 PostCreateView
则用于创建新的帖子。
基于类的视图(Class-Based Views, CBVs):
View
, TemplateView
, ListView
, DetailView
等。PostDetailView:
DetailView
,用于显示单个对象的详细信息。PostCreateView:
CreateView
,用于创建新的数据库记录。当从 PostDetailView
导航到 PostCreateView
并返回时出现 404 错误,可能的原因包括:
PostCreateView
的 URL 可能没有正确配置,导致 Django 无法找到对应的视图。PostCreateView
。确保 PostCreateView
的 URL 在 urls.py
中正确配置:
from django.urls import path
from .views import PostDetailView, PostCreateView
urlpatterns = [
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/create/', PostCreateView.as_view(), name='post-create'),
]
确保 PostCreateView
使用的模板文件存在且路径正确:
# views.py
from django.views.generic.edit import CreateView
from .models import Post
class PostCreateView(CreateView):
model = Post
template_name = 'posts/post_form.html'
fields = ['title', 'content']
如果需要权限控制,可以在视图中添加权限检查:
from django.contrib.auth.mixins import LoginRequiredMixin
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
template_name = 'posts/post_form.html'
fields = ['title', 'content']
确保在创建帖子后正确设置重定向 URL:
from django.urls import reverse_lazy
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
template_name = 'posts/post_form.html'
fields = ['title', 'content']
success_url = reverse_lazy('post-list') # 假设有一个名为 'post-list' 的 URL
通过以上步骤,应该能够解决从 PostDetailView
导航到 PostCreateView
并返回时出现的 404 错误。如果问题仍然存在,建议检查 Django 的日志文件以获取更多详细的错误信息。
领取专属 10元无门槛券
手把手带您无忧上云