Search code examples
djangodjango-views

redirect in view not finding url path or html template


I am trying to redirect from one view to another view or url name but getting errors regardless of what type of redirect I use. My preference is to use the view name to avoid hard coding the url.

Relevant views snippets involved:

main view snippet

        if form.is_valid():
            """ check if passwords match """
            print('form is valid')
            password1 = form.cleaned_data.get('password1')
            password2 = form.cleaned_data.get('password2')
            if password1 and password2 and password1 != password2:
                raise messages.add_message(request, messages.error, "Passwords don't match")
                return redirect('/members:new_profile')

            """ create user, set hashed password, redirect to login page """
            print('creating user')
            user = form.save(commit=False)
            user.set_password(password1)
            user.save()
            return redirect('members:user_login')

user_login view

def UserLogin(request):
    """ Member authenticate, set session variables and login """
    if request.method == 'POST':
        username = request.POST.get('email')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                """ set session expiry and variables with login"""
                login(request, user)
                request.session.set_expiry(86400)
                watchlist_items = Watchlist.objects.filter(created_by_id=user.id, status=True).values_list('listing_id', flat=True)
                print(f"watchlist_items: {watchlist_items}")
                if watchlist_items:
                    request.session['watchlist'] = list(watchlist_items)
                    print(f"watchlist session variable: {request.session['watchlist']}")
                    messages.add_message(request, messages.success, 'You have successfully logged in')
                else:
                    request.session['watchlist'] = []
                    messages.add_message(request, messages.success, 'You have successfully logged in')
                return redirect('general/dashboard.html')
            else:
                """ user has old account, prompt to reactivate and pay new subscription """
                messages.add_message(request, messages.error, 'This account is no longer active, please reactivate '
                                                           'account (subscription required)')
                return redirect('members/member_login.html')
        else:
            messages.add_message(request, messages.error, 'Username or password is incorrect')
            return redirect('members/member_login.html')
    else:
        return redirect('members/member_login.html')

members/urls.py

from django.urls import path
from members import views

app_name = 'members'

urlpatterns = [
    path('new_profile/', views.NewUserCreate, name='new_profile'),
    path('user_login/', views.UserLogin, name='user_login'),
    path('user_logout/', views.UserLogout, name='user_logout'),
]

project level urls.py

urlpatterns = [
    path('accounts/', include('django.contrib.auth.urls')),
    path('', include('general.urls')),
    path('members/', include('members.urls')),
    path("__debug__/", include("debug_toolbar.urls")),
]

In the main view code I have tried the following with different issues:

return HttpResponseRedirect(reverse('members:user_login'))

return redirect('user_login') - error NoReverseMatch at /members/new_profile/

return redirect('members:user_login') - Page not found error, lists url as http://127.0.0.1:8000/members/user_login/members/member_login.html

return redirect('/members:user_login') - page not found error, tries url http://127.0.0.1:8000/members:user_login

I know this should be a simple thing to do and I have redirects working for other views, cant figure out the best solution here, any help would be appreciated.


Solution

  • In your code, I found the problem with the way you have written the redirect. The correct syntax is:

    return redirect('app_name:url_name')
    

    and also you are trying to redirect to HTML page in user_login view which is not possible, instead you have to render the HTML page like this

    return render(request, 'members/member_login.html')
    

    Additional Info

    i notice that you have written the view name in CamelCase which is not correct instead you have to write in snake_case

    I hope this has been helpful for you. Happy Coding.