django - 在 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)
解决方案
我假设您正在尝试访问此 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'),
...
希望对您有所帮助,如果您还有任何问题,请随时与我联系。
推荐阅读
- javascript - 只能通过 HTML Canvas JavaScript 中的 Apple Pencil 进行输入
- regex - 如何改变一个和弦
标记为粗体
- jquery - 无法加载资源和状态文本是 ajax jquery 中的错误
- asp.net - 无法将当前 JSON 数组反序列化为类型模型,因为该类型需要 JSON 对象才能正确反序列化
- python - 如何以三列关系从 SQLAlchemy ORM 中检索正确的对象?
- python - 嗨,当测试包含 os.path.join() 时,我遇到了 runner.invoke() 的问题
- handlebars.js - 像应用程序一样的 vue 中的车把编译错误:期望 'ID',得到 'INVALID'
- python - 如何单击包含带有 seleniumbase 的文本的元素?
- mysql - mysql迁移工具包>>客户端不支持服务器请求的认证协议;考虑升级MySQL客户端报错
- wordpress - 在 Wordpress Woocommerce 网站中集成 Shipping API