Try/except in django, good practices

djangoexception handlingtry-catch

This part of code represents a index of my web page
eg: 127.0.0.1:8000/

def IndexView(request):
    try:
        profile = request.user.get_profile() 
    except User.DoesNotExist:
        return render_to_response('index.html',
                              {'request': request,},
                              context_instance=RequestContext(request))

    return render_to_response('index.html',
                  {'request': request, 'profile' : profile},
                  context_instance=RequestContext(request))  

Why i'm still getting this error on debug?

AttributeError at /
'AnonymousUser' object has no attribute 'get_profile'

thanks in advance

Best Answer

You need to add this check:

from django.shortcuts import render

def index_view(request):

    if request.user.is_authenticated():
        profile = request.user.get_profile()
        return render(request,'index.html',{'profile': profile})
    else:
        return redirect('login/')

Or, you can use the built-in decorator which ensures that your view is only called with a logged in user:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def index_view(request):

    profile = request.user.get_profile()
    return render(request,'index.html',{'profile': profile})

If you use the login_required decorator you need to make sure you have a LOGIN_URL setting that points to the view that handles the login form for your site. By default this is /accounts/login/

I changed the method name to lowercase as CamelCase is usually for classes in Python. Also, you don't need two return statements since you are rendering the same template. Instead, in your index.html template you can do:

{% if profile %}
    You have a profile!
{% else %}
    You don't
{% endif %}

Tips and tricks with authentication are listed at the authentication entry in the documentation.

Related Topic