简体   繁体   English

Django网址和视图无法传递参数

[英]Django Url and Views cant pass parameters

I am using Django 2.1.4 I Want to Pass a parameter like question_id in the url but i just get 404 . 我正在使用Django 2.1.4,我想在url中传递诸如question_id之类的参数,但我只得到404。

This is My Code : 这是我的代码:

urls.py : urls.py:

urlpatterns = [
    path('index',views.index , name='index'),
    path('index/(?P<question_id>[0-9])',views.detail , name='detail'),
]

and this is my : 这是我的:

view.py view.py

def index(request,):
    return HttpResponse("Welcome To My Page")

def detail(request, question_id):
    return HttpResponse("new Page" + str(question_id))

When I Enter http://127.0.0.1:8000/polls/index/12 in the url , i just get 404 . 当我在网址中输入http://127.0.0.1:8000/polls/index/12时,我只得到404。

I think that's the old (prior to 2.0) notation. 我认为这是旧的(2.0之前的)表示法。 I use 我用

path('profile/edit_avatar/<int:avatar_id>', views.edit_avatar, name='edit_avatar')

in my urls.py and 在我的urls.py和

def edit_avatar(request, avatar_id=0):

in my views (with a default value, just in case) 在我的视图中(以防万一,使用默认值)

See the Django tutorial , especially page 3 . 请参阅Django 教程 ,尤其是第3页

With Django 2.1.4 the path method can parse params in the URL with the following syntax: 在Django 2.1.4中, path方法可以使用以下语法来解析URL中的参数:

urlpatterns = [
    path('index',views.index , name='index'),
    path('index/<int:question_id>', views.detail , name='detail'),
]

If you want to stick to the good old regex, you should probably change your 'detail' view to 如果您想使用旧的正则表达式,则可能应该将“详细信息”视图更改为

path('index/(?P<question_id>[0-9]+/$)',views.detail , name='detail')

See also this article for more information. 另请参阅本文以获取更多信息。

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

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