当我要添加项目或转到project_create
URL时,出现错误提示。
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/project/add/
Raised by: projects.views.project_detail_view
URL告诉/project/add/
,根据视图它必须打开project_create_view
,但是详细视图projects.views.project_detail_view
会引发错误。
这是URL:
path('project/<slug:project_slug>/delete/',
project_delete_view, name='project_delete'),
path('project/<slug:project_slug>/update/',
project_update_view, name='project_update'),
path('project/<slug:project_slug>/',
project_detail_view, name='project_detail'),
path('projects/list/', all_projects_view, name='all_projects'),
path('project/add/', project_create_view, name='project_create'),
path('administration/', administration, name='administration'),
path("", home, name='home'),
如果我在path('project/<slug:project_slug>/',project_detail_view, name='project_detail'),
这一行中添加注释,那么project_create
的网址将转到正确的视图和正确的模板。为什么会这样呢?我使用了不同的name
,url
和view
名称。为什么会这样?
编辑:我添加了两个视图
@login_required
def project_create_view(request):
if not request.user.is_superuser:
raise PermissionDenied
if request.method == 'POST':
form = ProjectForm(request.POST, request.FILES)
if form.is_valid():
title = form.instance.title
form.save()
project = get_object_or_404(Project, title=title)
messages.success(request, 'Project created successfully.')
return redirect(project.get_absolute_url())
form = ProjectForm()
return render(request, 'projects/project_create.html', {'form': form})
def project_detail_view(request, project_slug):
project = get_object_or_404(Project, slug=project_slug)
session_key = 'project_views{}'.format(project.slug)
if not request.session.get(session_key, False):
Project.objects.filter(id=project.pk).update(
visit_count=F('visit_count') + 1
)
request.session[session_key] = True
context = {
'project': project
}
return render(request, 'projects/project_detail.html', context)
答案 0 :(得分:0)
动态网址必须在列表的底部,
urlpatterns = [
# Fixed URLs
path("", home, name='home'),
path('administration/', administration, name='administration'),
path('project/add/', project_create_view, name='project_create'),
path('projects/list/', all_projects_view, name='all_projects'),
# Dynamic URLs
path('project/<slug:project_slug>/',
project_detail_view, name='project_detail'),
path('project/<slug:project_slug>/delete/',
project_delete_view, name='project_delete'),
path('project/<slug:project_slug>/update/',
project_update_view, name='project_update'),
]
答案 1 :(得分:0)
您可以按应用或路径进行排序,例如,如果您有多个以project
开头的地址,则可以将它们分组在不同的网址格式列表中。
projecturls =[
# your project path urls
]
urlpatterns =[
path('project/', include(projecturls)),
# ...
]