how to properly redirect from one app to another app in django

Viewed 5191

i am a beginner to Django and i am unable to properly handle redirects from one app to another. I have 2 apps Accounts, Dashboard. Accounts Handles login and registration of AuthUser. Dashboard handles other functionality like Fileupload

So far, I have successfully using reverse() method have redirected from /accounts/login to my upload page but it redirects from /accounts/login to /accounts/upload instead of /dashboard/upload .

Project URLS

urlpatterns = [
    path('dashboard/', include('Dashboard.urls')),
    path('accounts/', include('Accounts.urls')),
    path('admin/', admin.site.urls),
]

Account urls.py

urlpatterns = [
    url('upload',DashboardViews.upload, name='upload'),
    path('login', views.login, name='Login'),
    path('register', views.register, name='Register'),
    path('logout', views.logout, name='logout')
]

Account views.py

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    if request.method == 'POST':

        user_name = request.POST.get("username")
        password = request.POST.get("password")

        user = auth.authenticate(username=user_name,password=password)

        if user is not None:
            auth.login(request,user)
            return redirect(reverse('upload'))
        else:
            print('Failed') 
            return render(request,'login')

My intention is whenever user (login/register), web page should redirect from /account/login to /dashboard/upload.

2 Answers

This is because you have the upload url defined in the urlpatterns of your Accounts app.
You should place it in the urls.py file from the Dashboard app if you want the full path to be /dashboard/upload, instead of /accounts/upload.

To explain it a bit more, when you define a path with the include function, like this:

   path("accounts/", include("Accounts.urls")

All the urls from the Accounts app will have "accounts/" appended at the beginning.

Note: If you add the name parameter to a path, you can use it in all your apps with the reverse function. The path doesn't have to be declared in the same app where you want to call the reverse function.

A good practice to avoid having url conflicts is to add the name of the app to the url. So you should maybe name the upload path as dashboard_upload.

I faced the same problem, but below technique worked for me.

In your urls.py file of Dashboard app, use app_name = "Dashboard". then in your redirect() function use appName:Path structure. For example, use redirect('Dashboard:upload')

Related