首页 > 解决方案 > 在 django 中使用双 url 标签

问题描述

我有两个 urls.py 文件

第一个用于项目 urls.py

urlpatterns = [
    path('admin/', admin.site.urls , name = 'admin'),
    path('',homeView, name='home'),
    path('post/',post, name='post'),
    path('post/',include('post.urls'), name='posturl'),
    path('student/',studentM, name = 'student' ),
    path('student/',include('student.urls') , name='studenturl'),
    
] 

第二个是应用程序的网址

 urlpatterns = [

    path('index', post_index, name = 'index'),
    path('details/' + '<int:id>', post_detail, name = 'detail'),
    path('create', post_create, name = 'create'),
    path('update', post_update , name = 'update'),
    path('delete', post_delete , name = 'delete'),

]

我正在尝试访问地址,例如 :8000/post/details/5 但是当我尝试在 html 中使用时

<a href = "{ % url 'post.detail' %}"> =>> {{post.id}}</a> 
<a href = "{ % url 'detail' %}"> =>> {{post.id}}</a>
<a href = "{ % url 'post' %}"> =>> {{post.id}}</a>

这些都不起作用我收到 404 错误。

我怎样才能到达我想要的链接

def post(request):
    context = {
    }
    return render(request,'post/post.html',context)

def post_detail(request,id):
    post = get_object_or_404(Post,id=id)
    context = {
        'post' : post
    }
    return render(request,"post/details.html",context)

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


我假设您正在尝试访问此 url 模式:

path('details/' + '<int:id>', post_detail, name = 'detail'),

可以这样写:

path('details/<int:id>/', post_detail, name='detail'),

如果我是正确的,你应该在你的 html 中使用这个标签:

<a href="{ % url 'appname:detail' post.id %}">text for the link</a>

另外,尽量不要这样做:

path('post/',post, name='post'),
path('post/',include('post.urls'), name='posturl'),

在您的应用程序中创建视图是更好的做法post,然后您的 urls.py 将如下所示:

# this is the project urls file
...
path('post/', include('post.urls')), # dont need a name here, you are not going to reference this
...
# this is the app urls file
...
path('', post, name='post'), # this is going to accessed as localhost:8000/post
path('index', post_index, name = 'index'),
path('details/<int:id>', post_detail, name = 'detail'), # this is going to accessed as localhost:8000/post/details/the_id_of_the_post
path('create', post_create, name = 'create'),
path('update', post_update , name = 'update'),
path('delete', post_delete , name = 'delete'),
...

希望对您有所帮助,如果您还有任何问题,请随时与我联系。


推荐阅读