Home > Mobile >  How can i redirect to same page for certain routes in Django?
How can i redirect to same page for certain routes in Django?

Time:07-15

enter image description here

i would like to restrict signup page after user is logged in so, if user is logged in then return back to same page

CodePudding user response:

Try the following:

from django.shortcuts import render, redirect
def signup_view(request):
    if request.user.is_authenticated:
        return redirect("home")
    else:
        return render("signup_page")

Another simple way would be to just change the button, that redirects to your registration page to something like "profile" and redirect to profile page: Change login text button to logout and vice versa

CodePudding user response:

I can't quite well get your question. But you want the new user to signup and when logged in return to signup page or home page?

If you want the logged in user to go to home page when he/she returns without the need to login or registering you can use redirect()

Your views.py :

from django.shortcuts import render, redirect
def registerPage(request):
form = CustomUserCreationForm()
if request.method == 'POST':
    form = CustomUserCreationForm(request.POST)
    if form.is_valid():
        user = form.save(commit=False)
        user.save()
        messages.success(request, 'Account successfuly created!')

        user = authenticate(request, username=user.username, password=request.POST['password1'])

        if user is not None:
            login(request, user)

        next_url = request.GET.get('next')
        if next_url == '' or next_url == None:
            next_url = 'home'
        return redirect(next_url)
    else:
        messages.error(request, 'An error has occured with registration')
context = {'form': form}
return render(request, 'register.html', context)
  • Related