Django url pattern - string parameter

前端 未结 6 576
面向向阳花
面向向阳花 2021-02-06 21:10

Django url pattern that have a number parameter is:

url(r\'^polls/(?P\\d+)/$\', \'polls.views.detail\')

What will be the correct

相关标签:
6条回答
  • 2021-02-06 21:25

    In newer versions of Django such as 2.1 you can use

    path('polls/<str:poll_id>', views.polls_detail)
    

    as given here Django URL dispatcher

    def polls_detail(request,poll_id):
    #process your request here
    
    0 讨论(0)
  • 2021-02-06 21:31

    Depends on what characters you care about. Like the docs say, \w will give you an alphanumeric character or an underscore.

    0 讨论(0)
  • 2021-02-06 21:33

    Starting in Django 2.0 it is easier to handle string parameters in URLs with the addition of the slug symbol, which is used just like int in urls.py:

    from django.urls import path
    
    urlpatterns = [
        path('something/<slug:foo>', views.slug_test),
    ]
    

    And in your function-based or class-based view you would handle it just like any other parameter:

    def slug_test(request, foo):
        return HttpResponse('Slug parameter is: ' + foo)
    
    0 讨论(0)
  • 2021-02-06 21:34

    If you are using Django version >= 2.0, then this is done simply like below.

    from django.urls import path    
    
    urlpatterns = [
        ...
        path('polls/<string>/$','polls.views.detail')
        ...
    ]
    

    Source: https://docs.djangoproject.com/en/2.0/ref/urls/#django.urls.path

    0 讨论(0)
  • 2021-02-06 21:37

    for having a string parameter in url you can have: url like this:

    url(r'^polls/(?P<string>[\w\-]+)/$','polls.views.detail')
    

    This will even allow the slug strings to pass eg:strings like node-js etc.

    0 讨论(0)
  • 2021-02-06 21:47

    From Django 2.0 onward, path has been introduced. path does not take reg ex in urls, hence it is meant to be a simplified version of the older url

    From 2.0 onward you can use path instead like below :

    path('polls/<poll_id>', views.polls_detail)
    

    string path parameters need not be explicitly specified, as default data type for path parameters is string itself.

    Ref : https://docs.djangoproject.com/en/2.0/releases/2.0/#whats-new-2-0

    0 讨论(0)
提交回复
热议问题