129-django工程中,在views函數里,讓頁面跳轉到其他app的模板頁面(跨app跳轉)


兩個工程都是一模一樣的格局,定義自己的urls.py文件,include到項目的根urls里,然后編寫自己的views函數,自己的templates。

 

要實現跳轉很簡單,首先看原來的views函數:

 

from django.shortcuts import render, get_object_or_404, reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from .models import ExUser
from .forms import UserLoginForm, UserRegForm


def login(request):
    if request.method != 'POST':
        form = UserLoginForm
        context = {'form': form}
        return render(request, 'login.html', context)
    else:
        username = request.POST['username']
        password = request.POST['password']
        login_user = authenticate(request, username=username, password=password)
        if login_user is not None:
            return HttpResponseRedirect(reverse('simplesite:login_ok'))
        else:
            return HttpResponse('login wrong!')

  

可以發現,當登錄成功后,需要跳轉到其他app的頁面,比如是一個登錄成功后的頁面。因為我們為注冊和登錄功能專門設置了一個app,而實際的內容肯定放在另一個app里,這就涉及到了跨app跳轉。

具體的做法是:

先完成2個引用:

from django.shortcuts import render, get_object_or_404, reverse
from django.http import HttpResponseRedirect, HttpResponse

然后使用寫法:

return HttpResponseRedirect(reverse('simplesite:login_ok'))

最關鍵的寫法是reverse里的內容:用引號包括,url的命名空間(通常等於app名稱): 某個path的名稱

 

完成這一步后,后續就是simplesite內部的邏輯,從url——》views函數——》模板。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM