【问题标题】:Using double url tag in django在 django 中使用双 url 标签
【发布时间】:2021-09-23 03:50:33
【问题描述】:

我有两个 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)

【问题讨论】:

标签: django django-models django-views django-forms django-templates


【解决方案1】:

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

path('details/' + '&lt;int:id&gt;', post_detail, name = 'detail'),

可以这样写:

path('details/&lt;int:id&gt;/', post_detail, name='detail'),

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

&lt;a href="{ % url 'appname:detail' post.id %}"&gt;text for the link&lt;/a&gt;

另外,尽量不要这样做:

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'),
...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 2014-04-23
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2017-06-22
    • 2013-01-21
    相关资源
    最近更新 更多