Skip to content

Dict object has no attribute has_key in Django

I’ve got this error when getting remote IP in Django.

image 3

code:

if request.META.has_key('HTTP_X_FORWARDED_FOR'):
    ip = request.META['HTTP_X_FORWARDED_FOR']
    print("http_x_forwarded:", ip)
else:
    ip = request.META['REMOTE_ADDR']
    print("remote addr:", ip) 

This happened when using ‘request’ to get remote IP in Django 2.0 because “has_key” has been removed in Python 3.

The correct code:

    if ('HTTP_X_FORWARDED_FOR')in request.META:
        ip = request.META['HTTP_X_FORWARDED_FOR']
        print("http_x_forwarded:", ip)
    else:
        ip = request.META['REMOTE_ADDR']
        print("remote addr:", ip)
    return HttpResponse("This is index page")

Leave a Reply