一、總urls.py內容以下:django
from django.contrib import admin from django.urls import path from django.conf.urls import include from myblog import views urlpatterns = [ # path('admin/', admin.site.urls), path('', views.index), path('myblog/', include('myblog.urls')), ]
二、APP中的urls.py以下:函數
from django.urls import path from .views import * urlpatterns = [ path('login/', login, name='login'), # http://127.0.0.1:8000/myblog/detail/1/2/ 傳參article_id 和 eid path('detail/<article_id>/<eid>/', article_detail, name='detail'), ]
三、APP下的views.py文件:url
from django.shortcuts import render, reverse, redirect from django.http import HttpResponse def index(request): # 判斷用戶是否登陸,有用戶名跳到首頁,沒有跳到登陸頁面 username = request.GET.get('username') if username: return HttpResponse("首頁") else: # 1.寫死的話, 修改代碼時須要把, 全部路徑找出來改爲新的路徑 # login_url = 'myblog/login/' # 二、利用reverse函數反轉url:找到urls.py中name='login'的路徑 # login_url = reverse('login') # 三、當reverse須要傳參時 login_url = reverse('detail', kwargs={'article_id': 1, 'eid': 2}) return redirect(login_url) def login(request): return HttpResponse("登陸頁面") def article_detail(request, article_id, eid): text = '您的文章ID+eid是: %s' % article_id, eid return HttpResponse(text)