Django 2中的URl重定向问题

时间:2018-11-25 18:05:23

标签: django django-urls

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

enter image description here

应用程序的流程是 shadesProductUploader.urls 会将“”转发到 authSection进行登录,并且在成功登录后,用户应重定向到 mainSection'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'),
]

mainSection.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})

成功登录后,出现此错误。

enter image description here

我想念什么?不知道为什么我会看到一个Url of home / home /

1 个答案:

答案 0 :(得分: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获得了网址。