Question

I am facing a problem while building a Django web app. I want that if a user logs into his account, his session should be stored and when he agains visits the login page ,he should be redirected to his home page. Here is my code.

Views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

def index(request):
    return HttpResponse("Index Page")

@login_required
    def home(request):
ctx = {}
return render_to_response('auth/home.html',ctx, context_instance = RequestContext(request))

def login_page(request):
    if request.user.is_authenticated():
        return redirect('cc_home')
    else:
    return render_to_response(request,'auth/cc.html')

Urls.py

from django.conf.urls.defaults import *
from django.contrib.auth.views import login, logout

urlpatterns = patterns('',
url(r'cc/', 'apps.auth.views.login_page', name = 'cc_login'),
url(r'logout/', logout, name = 'cc_logout'),
url(r'home/','apps.auth.views.home', name = 'cc_home'),
)

And here is my template cc.html

    <form action ="." method = POST>
        {% csrf_token %}    
        {{ form.as_p }}
        <input type = "submit" value = "login">
    </form>


</body>

home.html

{{ user }} 's profile
<a href = "{% url 'cc_logout' %}">Logout</a>

When I browse to CC url it should first asks the user's credentials. After successful login, it should redirect to the user's home url, which is running fine. But, when the user again browse to CC url (), he should be redirected it to his home page.

While Debugging, I found that it is not able to render the form when the user is not authenticated. It does not shows the Django's inbuilt form provided in the CC.html, it just shows the Login button.

How do I render the form. Kindly suggest.

Thanks

Was it helpful?

Solution 3

May be the error is in the login_page method. try to fix it like this def login_page(request): if request.user.is_authenticated(): return redirect('cc_home') else: return render_to_response('auth/cc.html',{} context_instance = RequestContext(request)) i believe that the request in your render_to_response cause the problem

OTHER TIPS

But you haven't passed any form to the template to render! You need to instantiate the login form and pass it to the template context, otherwise {{ form }} doesn't refer to anything.

You should be able to use the default form if you replace;

url(r'cc/', 'apps.auth.views.login_page', name = 'cc_login'),

with;

url(r'cc/', login, {template_name: 'cc.html'}),
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top