为什么重定向功能会改变我在 django 中的 url

问题描述 投票:0回答:2

def login() 函数调用和 redirectdef index() 函数时,我的 url 在浏览器中发生变化,看起来像 http://127.0.0.1:8000/error500index 这个 url。但逻辑上 url 看起来像 http://127.0.0.1:8000/index 这个。但是当我使用重定向功能时,url中显示了error500,error500是我在Project urls.pyAPP urls.py中的最后一个url。
有人帮我看看发生了什么事吗?

view.py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.http import HttpResponse
from .models import WebUser

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

def login(request):
if (request.method == 'POST'):
    login_email = request.POST['email']
    login_password = request.POST['password']

    # Compare with Database where input email exist!
    try:
        CheckUser = WebUser.objects.get(email=login_email)
    except:
        return HttpResponse("User Dosen't Exist!")

    if (login_email == CheckUser.email and login_password == CheckUser.Password):
        
       #When redirect function call my url change and pick the last url from project urls.py and this url appears in the browser http://127.0.0.1:8000/error500index
        return redirect(index)
    else:
        return HttpResponse("Email or Password are wrong!")

else:
    return render(request, 'login.html')

项目 URL.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('SIS_APP.urls')),
    path('index', include('SIS_APP.urls')),
    path('login', include('SIS_APP.urls')),
    path('register', include('SIS_APP.urls')),
    path('settings', include('SIS_APP.urls')),
    path('weather', include('SIS_APP.urls')),
    path('error404', include('SIS_APP.urls')),
    path('error500', include('SIS_APP.urls')),
]

APP urls.py

from django.contrib import admin
from django.urls import path

from . import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('index', views.index, name='index'),
    path('login', views.login, name='login'),
    path('register', views.register, name='register'),
    path('settings', views.settings, name='settings'),
    path('weather', weatherAPI.weather, name='weather'),
    path('error404', views.error404, name='error404'),
    path('error500', views.error500, name='error500'),
] 
python django django-views django-urls
2个回答
1
投票

您的网址中缺少斜杠“/”。 URL 是串联的,所以如果你有,即

path('index', views.index, name='index'), ## this will give ..indexsome-sub-route
path('index/', views.index, name='index'), ## this will give ..index/some-sub-route

0
投票

我认为您没有正确定义 URL。来自 Django 文档

您将看到重定向可以与硬编码链接一起使用,即:

redirect("/index/")

由于您没有在 URL 中添加斜杠,我们有:

redirect("index")

因此它会将值索引传递给您的 URL。要修复此问题,请将

/
添加到您的 URL 定义中。

© www.soinside.com 2019 - 2024. All rights reserved.