1、總urls.py內容如下:
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')), ]
2、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'), ]
3、APP下的views.py文件:
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/' # 2、利用reverse函數反轉url:找到urls.py中name='login'的路徑 # login_url = reverse('login') # 3、當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)