django跳转页面传参
1、如果在反转url的时候,需要添加参数,那么可以通过传递'kwargs'参数到'reverse'函数中。实例代码:
urls.py
from django.urls import path, re_path from app01 import views urlpatterns = [ path('article/<year>/<month>/',views.article,name='article'), path('', views.Login.as_view(), name="login"), ]
views.py
from django.shortcuts import HttpResponse, redirect, reverse from django.contrib.auth.models import User, from django.views.generic import View from django.contrib.auth import authenticate, login, class Login(View): def get(self, request): return render(request, 'login.html') def post(self, request): username = request.POST.get('username') passwd = request.POST.get('passwd') user = authenticate(request, username=username, password=passwd) if user is not None: if user.is_active: login(request, user) # 登录成功跳转页面 return redirect(reverse('article', kwargs={'year': 2019, 'month': 12})) else: err_msg = '用户未激活,请联系管理员进行激活' else: err_msg = '用户名或密码有误' return render(request, 'login.html', {"err_msg": err_msg, "username": username}) def article(request, year, month): return HttpResponse('您查询的文章日期是:%s年%s月' %(year, month))
2、如果想要添加查询字符串的参数,则必须手动的进行拼接。实例代码如下:
login_url = reverse('login')+"?next=/"