【发布时间】:2021-11-05 22:05:59
【问题描述】:
当 def login() 函数调用和 redirect 到 def index() 函数时,我的 url 在浏览器中发生变化,看起来像 http://127.0.0.1:8000/error500index 这个网址。但逻辑上 url 看起来像 http://127.0.0.1:8000/index 这个。但是当我使用重定向功能时,error500 会显示在 url 中,error500 是我在 Project urls.py 和 APP 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')
项目 Urls.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'),
]
【问题讨论】:
-
你好@Mujahid,如果你想使用重定向到特定的应用程序url,你必须像这样使用
redirect('your_app_name:your_url_name'),其中url_name是你的url示例的名称name='index'
标签: python django django-views django-urls