【问题标题】:URl redirection issue in Django 2Django 2 中的 URl 重定向问题
【发布时间】:2018-11-25 18:05:23
【问题描述】:

我是 Django 新手,正在尝试构建具有以下结构的 Web 应用程序。我需要你的帮助来了解我做错了什么。

应用程序的流程是 shadesProductUploader.urls 将 '' 转发到 authSection 以进行登录 并在成功登录后将用户重定向到 ma​​inSection 'home /'.

Urls.py 文件是

shadesProductUploader.urls

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('authSection.urls')),

]

authSection.urls

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

app_name = 'authSection'

urlpatterns = [
path('', views.login_view, name='login'),
]

ma​​inSection.urls

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

app_name = 'mainSection'

urlpatterns = [
path('home/', views.home),
]

和 authSection 中的 view.py

def login_view(request):
next = request.GET.get('next')
form = userLoginForm(request.POST or None)
if form.is_valid():
    username = form.cleaned_data.get('username')
    password = form.cleaned_data.get('password')
    user = authenticate(username=username,password=password)
    login(request,user)
    if next:
        return redirect(next)
    context={'user':user}
    return redirect('home/')
return render(request, 'login.html', {'form': form})

成功登录后出现此错误。

我错过了什么?不知道为什么我会看到 home/home/ 的网址

【问题讨论】:

    标签: django django-urls


    【解决方案1】:

    像这样更新shadesProductUploader的主要部分网址:

    urlpatterns = [
            path('',include('mainSection.urls')),
            ... # other urls
        ]
    

    并像这样更改 mainSection 网址:

    urlpatterns = [
        path('home/', views.home, name="home"),  # <-- added name here
    ]
    

    在视图中,像这样使用它:

    if next:
        return redirect(next)
    context={'user':user}
    return redirect(reverse('home'))
    

    在这里,我们有named 我们的网址为home。我们使用reverse 获得了网址。

    【讨论】:

    • 它工作了,但现在我的 ShadesProductUploader 看起来像 urlpatterns = [ path('',include('mainSection.urls')), path('admin/', admin.site.urls), path ('',include('authSection.urls')), ] 它如何确定后面跟着哪个''?
    • 您可以在文档中了解它:docs.djangoproject.com/en/2.1/topics/http/urls/…
    猜你喜欢
    • 2012-10-07
    • 2018-02-14
    • 1970-01-01
    • 2016-01-01
    • 2018-05-22
    • 2014-04-03
    • 2021-03-30
    • 1970-01-01
    相关资源
    最近更新 更多