将用户重定向到主页 django 的问题

Posted

技术标签:

【中文标题】将用户重定向到主页 django 的问题【英文标题】:issue in redirecting user to home page django 【发布时间】:2021-01-02 01:21:11 【问题描述】:

当我尝试登录时,它不会将我重定向到主页。相反,它向我显示了一个错误 网址应该是http://127.0.0.1:8000/ 它显示http://127.0.0.1:8000/login 我尝试同时使用函数名和路径名

urls.py

app_name = "accounts"

urlpatterns = [
    path('', views.home,name="home"),
    path('register/',views.register, name='register'),
    path('login/',views.loginPage, name='login')]

views.py

def loginPage(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request,username=username, password=password)
        if user is not None:
            login(request,user)
            return redirect('home')
    return render(request,'accounts/login.html')

错误

NoReverseMatch at /login/
Reverse for 'home' not found. 'home' is not a valid view function or pattern name.
Request Method: POST
Request URL:    http://127.0.0.1:8000/login/
Django Version: 3.0.4
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'home' not found. 'home' is not a valid view function or pattern name.
Exception Location: C:\Users\Mahmoud Ishag\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677

【问题讨论】:

home 更改为accounts:home 【参考方案1】:

在 views.py 中,url 名称的工作方式与在模板中时不同。

您可以尝试将return redirect('home') 更改为return redirect('')return redirect('/'),具体取决于您在path('', views.home, name="home") 中定义URL 的方式。

【讨论】:

以上是关于将用户重定向到主页 django 的问题的主要内容,如果未能解决你的问题,请参考以下文章

django:登录后重定向到引用页面[重复]

Django 使用绑定表单重定向到另一个视图

如何将已通过身份验证的用户从登录页面重定向到主页

如何在访问主页时将用户重定向到特定 URL?

当我有“下一个”网址时,如何禁用网址重定向? - 姜戈

如何重定向到主页