I have created a blog with Django and whenever a user logs in, the URL redirects to the homepage and displays a success message. This is fine, however, whenever a login is required to view a certain page, Django redirects to the login page and attaches "?next=" to the end of the URL to redirect back to the previous page. The problem is that after the user logs in, the "next" URL is not executed and Django redirects to the homepage and displays the success message? Is there a way to disable this redirect whenever there is a "next" URL?
views.py
from django.urls import reverse
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth import login
from django.utils.safestring import mark_safe
from .forms import UserLoginForm
def login_view(request):
if request.method == 'POST':
form = UserLoginForm(data=request.POST)
if form.is_valid():
student = form.get_user()
login(request, user)
create_url = reverse('post-create')
messages.success(request, mark_safe(f'You are now logged in. Do you want to <a href="{ create_url }" class="link" title="Create a post">create a post</a>?'))
return redirect('home')
else:
form = UserLoginForm()
return render(request, 'users/login.html', {'form': form, 'title': 'Log in'})
You can get this next
url from request.GET
and default to your homepage if it's not there
return redirect(request.GET.get('next', 'home'))
This way, if ?next=...
is in the query parameters it will be used as the redirect path, if it's not then you will redirect to 'home'