Django routing/pathing 增加应用程序

Django routing/pathing to multiply apps

您好,我知道有很多人询问有关从一个视图路由到 Django 中的一个新应用程序的问题。我看过很多。并想出使用 app_name = 'name' 并为我的 html 模板使用命名路由肯定会让一切变得更容易。当我尝试使用 app_name:named-route 时,我得到了这个:

/recipedashboard 处的值错误 视图 recipeApp.views.dashboard 没有 return HttpResponse 对象。它 return 改为 None。

我已经获得 name_app:named-route 将我发送到第二个应用程序,但我如何将会话传递给新应用程序?

userApp 查看:

from django.shortcuts import render, redirect
from django.contrib import messages
from .models import User as LoggedUser

# Create your views here.

def index(request):
    return render(request, 'index.html')

def register(request):
    if request.method == "GET":
        return redirect('/')
    errors = LoggedUser.objects.validate(request.POST)
    if len(errors) > 0:
        for er in errors.values():
            messages.error(request, er)
        return redirect('/')
    else:
        new_user = LoggedUser.objects.register(request.POST)
        request.session['user_id'] = new_user.id
        messages.success(request, "You have successfully registered")
        return redirect('/success')

def login(request):
    if request.method == "GET":
        return redirect('/')
    if not LoggedUser.objects.authenticate(request.POST['email'],
        request.POST['password']):
        messages.error(request, "Invalid Email/Password")
        return redirect('/')
    user = LoggedUser.objects.get(email=request.POST['email'])
    request.session['user_id'] = user.id
    messages.success(request, "You have successfully logged in!")
    return redirect('/success')

def logout(request):
    request.session.clear()
    return redirect('/')

def success(request):
    if 'user_id' not in request.session:
        return redirect('/')
    context = {
        'user' : LoggedUser.objects.get(id=request.session['user_id'])
    }
    return redirect("recipe:recipe-dashboard")

食谱应用urls.py:

from django.urls import path
from . import views as recipeViews
app_name ='recipe'


urlpatterns = [
    path('dashboard', recipeViews.dashboard, name= "recipe-dashboard" )
] 

recipeApp.Views :

from django.shortcuts import render, redirect
from userApp.models import User as LoggedUser

# Create your views here.
def dashboard(request):
    if 'user_id' not in request.session:
        return redirect('/')
    user = LoggedUser.objects.get(id=request.session['user_id'])
    context = {
        'user' : user
    }
    render (request, 'dashboard.html', context)

您的 dashboard 视图没有 returning 任何东西。

您需要return渲染结果。喜欢

from django.shortcuts import render, redirect
from userApp.models import User as LoggedUser

# Create your views here.
def dashboard(request):
    if 'user_id' not in request.session:
        return redirect('/')
    user = LoggedUser.objects.get(id=request.session['user_id'])
    context = {
        'user' : user
    }
    return render (request, 'dashboard.html', context)

无需处理通过会话。如果应用程序都在同一个项目下,框架将为您处理。