Best way of linking to a page in Django

前端 未结 5 2166
臣服心动
臣服心动 2021-02-08 20:02

I managed to create a URL tag for my index. But right now I\'m confused how to add links to other pages.

I put this on my urls.py

url(r\         


        
5条回答
  •  执笔经年
    2021-02-08 20:34

    Django has updated urlpatterns to take 'path' instead of using url so it's become much more efficient. You don't have to use regex anymore

    from django.urls import path
    from . import views
    
    urlpatterns=[
        path('', views.index , name='index'),
        path('blog/', views.blog , name='blog'),]
    

    Then in templates, you can use template tagging

    Index
    Blog
    

    If you have multiple apps, you can tag it as follows. For example, if this is under 'post' app:

    In post app urls.py:

    from django.urls import path
    from . import views
    
    app_name = 'post'
    urlpatterns=[
        path('', views.index , name='index'),
        path('blog/', views.blog , name='blog'),]
    

    in the project urls.py:

    from django.urls import path, include
    
    urlpatterns=[
    path('post/', include('post.urls'),]
    

    In templates, you do as following:

    Index
    Blog
    

提交回复
热议问题