Reputation: 109
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.
Upvotes: 5
Views: 7955
Reputation: 557
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')
Upvotes: 5
Reputation: 1325
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.
Upvotes: 3