Skip to content Skip to sidebar Skip to footer

How Can I Pass The Request If I Redirect And Then Render The Template

I have a requirement, from login page jump to the admin page, you know the URL address should change to the admin page. If I only use render to admin page, the URL address will no

Solution 1:

You should take a look at some basic Django tutorials, such as this one, which describes how to create a login handler.

The gist is this:

In the view where the user submit the form, you evaluate the username and/or password. If the submitted the correct information (username and password), then save this information in the session. Redirect the user to the logged in (restricted) area and check the session. If the session has the correct information, then allow the user to view the content, otherwise redirect the user out.

Simple login logic (illustrative):

deflogin(request):
    m = Member.objects.get(username=request.POST['username'])
    if m.password == request.POST['password']:
        # Username and password is correct, save that the user is logged in in the session variable
        request.session['logged_in'] = True
        request.session['username'] = request.POST['password']
        # Redirect the user to the admin pagereturn redirect('/app_admin/index/')
    else:
        # Username and/or password was incorrectreturn HttpResponse("Your username and password didn't match.")

Simple admin page logic (illustrative):

defadmin_index(request):
    # Make sure that the user is logged inif'logged_in'in request.session and request.session['logged_in']:
        # User is logged in, display the admin pagereturn render(
            request, 
            'app_admin/index.html', 
            {'username': request.session['username']}
        ) # You can now use {{ username }} in your view# User is not logged in and should not be here. Display error message or redirect the user to the login pagereturn HttpResponse("You are not logged in")

Note that these are two different views (and URLs), that you have to map up in your urlpatterns.

Post a Comment for "How Can I Pass The Request If I Redirect And Then Render The Template"