Django reverse函数
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)