Abhijeet Pal
Abhijeet Pal

Reputation: 468

Url mapping in django 2.0

so moving from Django 1.9 to Django 2 is not so smooth for me. I have struck in the URL patterns.

Django 2.0 uses path instead of URL, How to convert these URL patterns to Django 2.0 compatible?

url(r'^post/(?<pk>\d+)$',)views.PostDetailView.as_view(), name ='post_detail'),

url('account/login/', views.login, name ='login')

Thanks

Upvotes: 0

Views: 844

Answers (2)

JPG
JPG

Reputation: 88459

Method-1

By using path()

from django.urls import path

urlpatterns = [
    path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'),
    path('account/login/', views.login, name='login')
]

Method-2

You can use re_path() which behave same as url() does

from django.urls import re_path

urlpatterns = [
    re_path(r'^post/(?<pk>\d+)$', views.PostDetailView.as_view(), name='post_detail'),
    re_path(r'account/login/', views.login, name='login')
]

Method-3

From the doc, (What’s new in Django 2.0)

The django.conf.urls.url() function from previous versions is now available as django.urls.re_path(). The old location remains for backwards compatibility, without an imminent deprecation. The old django.conf.urls.include() function is now importable from django.urls so you can use from django.urls import include, path, re_path in your URLconfs.


So, you could use the same url() function in django 2.x (till the complete deprication) from the older location, as

from django.conf.urls import url

urlpatterns = [
    url(r'^post/(?<pk>\d+)$', views.PostDetailView.as_view(), name='post_detail'),
    url('account/login/', views.login, name='login')
]

Upvotes: 3

awesoon
awesoon

Reputation: 33651

Django 2.0 release notes covers your case (not exactly, but anyway) - your urls could be rewritten as follows (assuming you meant (?P<pk>\d+) - note the P just after ?):

path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'),
path('account/login/', views.login, name='login')

Upvotes: 2

Related Questions