简体   繁体   中英

Django redirecting to a wrong url

when i click submit on my form it goes to ../register/register/ where as my expectation is that it should go to ../register

This is my main project urls.py

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

This is my application urls.py

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

This is my views function

def register(request):
    if request.method == "POST":
        username = request.POST['username']
        # email = request.POST['email']
        password = request.POST['pass']
        print(username, password)
        user = User.objects.create_user(username=username, password=password)
        user.save()
        return redirect('register')

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

You can try adding namespaces to your urls

Main project urls.py

urlpatterns = [
    path('participants/', include('participants.urls', namespace='participants')),
    path('admin/', admin.site.urls),
]

Application urls.py

app_name = 'participants'
urlpatterns = [
    path('register/', views.register, name="register")
]

View

def register(request):
    if request.method == "POST":
    ...
    return redirect('participants:register')

您可以安装django-extensions并运行manage.py show_urls以找出您拥有的 url,还可以尝试reverse('register')检查它指向的位置。

use

return redirect('/register')

instead of

return redirect('register')

You would need the slash('/') at the front to let Django know that it's referencing the root of the named URL that is after the Hostname.

Without the slash, it'll just append to the current named URL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM