简体   繁体   English

Django Slugs 作为主要 url

[英]Django Slugs as principal url

I want to do the following, so that the profile of each registered user can be seen as follows: http://127.0.0.1:8000/username/我想做以下事情,以便可以看到每个注册用户的个人资料如下: http : //127.0.0.1 : 8000/ username/

I was able to achieve this, the problem is when wanting to create another page, for example http://127.0.0.1:8000/explore/我能够做到这一点,问题是想要创建另一个页面,例如http://127.0.0.1:8000/explore/

Django consider "explore" as a user and throw me a 404 error . Django 将“探索”视为用户并抛出404 错误

this is my urls.py这是我的urls.py

urlpatterns = [
    path("<slug:slug>/", PerfilView.as_view(), name="perfil"),
    path("explore/", UserListView.as_view(), name="explore"),
]

Am I doing it the right way or am I unable to do this with django?我是否以正确的方式做这件事,还是我无法用 django 做到这一点?

Regads瑞佳

You should swap the two path(…) : if you visit explore/ it will first match with the PerfilView since the slug can take 'explore' as value.您应该交换两个path(…) :如果您访问explore/它将首先与PerfilView匹配,因为 slug 可以将'explore'作为值。

You thus should rewrite the urlpatterns to:因此,您应该将urlpatterns重写为:

urlpatterns = [
    #       ↓ first explore
    path('explore/', UserListView.as_view(), name='explore'),
    path('<slug:slug>/', PerfilView.as_view(), name='perfil'),
]

This also means that you can not use explore as a slug here, since then it will match with the UserListView .这也意味着你不能在这里使用explore作为 slug,因为它会与UserListView匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM