Skip to content Skip to sidebar Skip to footer

'invalid Input Syntax For Type Inet' Db Error In Django App With Postgres And Gunicorn+nginx As Reverse Proxy

Can you help me decipher this rather esoteric error? Everything's fine when I fire up the application, but crashes the moment I try to login. DatabaseError at /login/ invalid inpu

Solution 1:

You are not forwarding proxy IP. Here is my set of forwarded headers I set in my nginx config:

location / {
    proxy_set_header    Host                    $http_host;
    proxy_set_header    User-Agent              $http_user_agent;
    proxy_set_header    X-Real-IP               $remote_addr;
    proxy_set_header    X-Forwarded-For$proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Proto       $scheme;
    proxy_pass          ......;
}

More options in nginx docs - http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header

Then in Django you can do:

user_ip = request.META['HTTP_X_REAL_IP`] or request.META['REMOTE_ADDR']

Note that X-Forwarded-Proto is necessary when using Django with SSL in which case you will also need to configure Django a bit:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

More in Django docs - https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-SECURE_PROXY_SSL_HEADER

Solution 2:

Your program is trying to add a row to some logging table with empty remote IP. I suppose that when you use reverse proxy the program doesn't know the remote IP, as it's shadowed by proxy's IP.

As it's empty I suppose the program is trying to ignore proxy's IP, but it does not find any better. It should use X-Forwarded-For header.

If there's no reasonable IP to log, the program should simply log "NULL" as the IP.

Solution 3:

Adding a custom middleware solved it:

classXForwardedForMiddleware():defprocess_request(self, request):
        if request.META.has_key("HTTP_X_FORWARDED_FOR"):
            request.META["HTTP_X_PROXY_REMOTE_ADDR"] = request.META["REMOTE_ADDR"]
            parts = request.META["HTTP_X_FORWARDED_FOR"].split(",", 1)
            request.META["REMOTE_ADDR"] = parts[0]

Post a Comment for "'invalid Input Syntax For Type Inet' Db Error In Django App With Postgres And Gunicorn+nginx As Reverse Proxy"