unable to get remote addr request.META ['REMOTE_ADDR'] not working - django

hi
i am unable to get ip address of the user connecting to my site under django 1.1.1.
ip_address=request.META['REMOTE_ADDR']
em using python 2.6 django 1.1.1 under ubuntu 10.10
i have also installed the middle ware and tried this method also
'django.middleware.http.SetRemoteAddrFromForwardedFor'
try:
ip_address=request.META['HTTP_X_FORWARDED_FOR']
except KeyError:
pass
else:
# HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
# Take just the first one.
ip_address = ip_address.split(",")[0]
request.META['REMOTE_ADDR'] = ip_address
and in the templates i also tried to get IP using {{ request.REMOTE_ADDR }}
but unable to get the IP
what will be the reason for this
any help wil be greatly appreaciated thanks

the problem is solved
i dont know what was the issue but re installation
of django solved solved the problem

Related

allowed_host changes not effective

I've got an address say example.com and have added it to the allowed_hosts list. But when I access the site I get
ALLOWED_HOSTS ['127.0.0.1', '::1', '178.XX.XX.XXX', 'xx80::xx81:xxx:xx3x:x12x%eth0']
in the debug error page, while the actual settings.py file reads ['178.XX.XX.XXX','example.com']. I figured the changes to settings.py aren't registered as I can remove 178.XX.XX.XXX from the list and still access the site (after clearing the browser cache) I've restarted nginx, gunicorn and the whole server to no avail. The whole thing is set up on ubuntu 16.04 running django 1.8 and using nginx and gunicorn. Any ideas where this override of allowed_hosts could be coming from?
Ok this is embarassing but the One-cick install for django on 16.04 from Digital Ocean adds a line at the very end of settings.py where ALLOWED_HOSTS is redefined.
# Find out what the IP addresses are at run time
# This is necessary because otherwise Gunicorn will reject the connections
def ip_addresses():
ip_list = []
for interface in netifaces.interfaces():
addrs = netifaces.ifaddresses(interface)
for x in (netifaces.AF_INET, netifaces.AF_INET6):
if x in addrs:
ip_list.append(addrs[x][0]['addr'])
return ip_list
# Discover our IP address
ALLOWED_HOSTS = ip_addresses()
ALLOWED_HOSTS.append('.example.com') #I added this line
So adding an append to the line fixes the problem.

Downloading a file with LDAP authentication

I'm trying to find a way to download a CSV from a network URI (not web) that requires LDAP authentication. I have a service account made for this, but I'm not able to find a working solution:
conn = ldap.open("10.41.10.10:389") #I've tried different URIs
conn.simple_bind_s('svc_acct#company.com', 'password')
call = open(r'\\fserv03\reports\gps_List.csv')
Is there a better way to do this?
Updated: Got Python-LDAP to work for my 64 bit install after downloading Python-LDAP to work, I downloaded python_ldap-2.4.28-cp27-cp27m-win_amd64 and running the pip install on it.
I was able to get this to work with the following (using Python-LDAP library):
try:
l = ldap.initialize('ldap://LDAP SERVER HERE')
l.protocol_version = ldap.VERSION2
username = "cn=USER, o=example.com"
password = 'PASSWORD HERE'
l.simple_bind(username, password)
except ldap.LDAPError, e:
print e

Django and Bad Request (400)

I created new django project;
added to my settings.py:
DEBUG = False
ALLOWED_HOSTS= [
'localhost',
'my_site.com'
]
created app test_view;
added hello_world to test_view.views
from django.http.response import HttpResponse
def hello_world(request):
return HttpResponse('Hello World!!!')
added test route to urls.py url(r'test/', 'test_view.views.hello_world');
fixed /etc/hosts
127.0.0.1 localhost my_site.com
Now when i'm trying to access http://my_site.com:8000/test/ django returns Bad Request (400). But when url is http://localhost:8000/test/ I can see my Hello World page. What can be wrong?
UPD:
The same result with DEBUG = True
UPD2:
One more working hostname is ubuntu-virtualbox (computer's name).
But even when I changed computer's name to my_site, ubuntu-virtualbox was still available and my_site returned Bad Request (400)
May it be because of some system settings? (it's clean ubuntu in virtualbox).
Or maybe problem in virtualenv? Is there a way to trace the error?
It might be a bad Cookie. Try deleting them.
It looks like django can see if request isn't passed through dns server. Installation and configuration of bind9 instead of changes in /etc/hosts solved this problem.
You need another line in your hosts file.
127.0.0.1 localhost
127.0.0.1 my_site.com
Then in your ALLOWED_HOSTS...
ALLOWED_HOSTS = [
'localhost',
'.my_site.com', # not 'my_site.com'
]
ALSO, and this is probably important seeing as you are running your site from a virtual machine, when you run the site with python manage.py runserver, run it like this...
python manage.py runserver virtual.server.ip.address:8000
Obviously replace 'virtual.server.ip.address' with that virtual machines actual ip address.
I print *DEBUG = None* and my django works.

builtin password reset view problem in django1.3

Hi am absolutely new to django,Now I am tring for builtin reset password view..
I follow the link link
But I got the error when I click on reset password button at /password_reset/ :
error at /accounts/password_reset/
[Errno 10061] No connection could be made because the target machine actively refused it.
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
'urls.py'
(r'^accounts/password_reset$','django.contrib.auth.views.password_reset','template_name':'user/password_reset_form.html','email_template_name':'user/password_reset_email.html'}),
(r'^accounts/password/reset/confirm/(?P[0-9A-Za-z]{1,13})-(?P[0-9Aa-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'django.contrib.auth.views.password_reset_confirm', {'template_name' : 'user/password_reset.html', 'post_reset_redirect': '/logout/' }),
(r'^accounts/password_reset/done/$',<b>'django.contrib.auth.views.password_reset_done'</b>,{'template_name':'user/password_reset_done.html'}),
(r'^accounts/change_password/$',<b> 'password_change'</b>, {'post_change_redirect' : '/accounts/change_password/done/'}),
(r'^accounts/change_password/done/$',<b> 'password_change_done'</b>,{'template_name':'user/password_change_done.html'}),
<b>password_reset_email.html</b>
{% extends 'base.html'%}
{% block content%}
{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %}
{% endblock %}
I add necessary templates in the folder 'user'.Please help me,Thanks in advance.
As rdegges said, it's a connection error. Check which port the request is trying to access, and make sure windows firewall is set up to receive on that port. You can check the port by looking through django's traceback page, and looking at the "local vars".
From the looks of it, it's an email port. Take another look at the traceback and look out for django trying to send a request to port 25. If it does, make sure your port 25 is configured to receive.
Also, you'll need a makeshift SMTP server for testing purposes because you probably wouldn't want to be using a real one. Just have this running in a separate command prompt window while you're running django, and any emails that django tries to send through your port 25 will be saved in an "emails" folder in the working directory.
#/usr/bin/env python
from datetime import datetime
import asyncore
from smtpd import SMTPServer
class EmlServer(SMTPServer):
no = 0
def process_message(self, peer, mailfrom, rcpttos, data):
filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'), self.no)
f = open(filename, 'w')
f.write(data)
f.close()
print '%s saved.' % filename
self.no += 1
def run():
foo = EmlServer(('localhost', 25), None)
try:
asyncore.loop()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
from os.path import exists, join
from os import mkdir, chdir, getcwd
target_directory = join( getcwd(), "emails" )
if exists(target_directory):
chdir(target_directory)
else:
try:
mkdir(target_directory)
except OSError:
from sys import exit
exit("The containing folder couldn't be created, check your permissions.")
chdir(target_directory)
print "Using directory %s" % target_directory
run()
The error you're getting is a connection error--that means that the server you're using to run your Django site is likely not working correctly. Here are some things you can try on your Django server:
If you're running your Django site via python manage.py runserver, you can try to simply re-run that command.
If you're running your site via a webserver like apache, try restarting apache.
If neither of those work, post a comment and let me know what operating system you're running your site on, and how you're running it, and we can do further debugging.

django generator function not working with real server

I have some code written in django/python. The principal is that the HTTP Response is a generator function. It spits the output of a subprocess on the browser window line by line. This works really well when I am using the django test server. When I use the real server it fails / basically it just beachballs when you press submit on the page before.
#condition(etag_func=None)
def pushviablah(request):
if 'hostname' in request.POST and request.POST['hostname']:
hostname = request.POST['hostname']
command = "blah.pl --host " + host + " --noturn"
return HttpResponse( stream_response_generator( hostname, command ), mimetype='text/html')
def stream_response_generator( hostname, command ):
proc = subprocess.Popen(command.split(), 0, None, subprocess.PIPE, subprocess.PIPE, subprocess.PIPE )
yield "<pre>"
var = 1
while (var == 1):
for line in proc.stdout.readline():
yield line
Anyone have any suggestions on how to get this working with on the real server? Or even how to debug why it is not working?
I discovered that the generator function is actually running but it has to complete before the httpresponse throws up a page onscreen. I don't want to have to wait for it to complete before the user sees output. I would like the user to see output as the subprocess progresses.
I'm wondering if this issue could be related to something in apache2 rather than django.
#evolution did you use gunicorn to deploy your app. If yes then you have created a service. I am having a similar kind of issue but with libreoffice. As much as I have researched I have found that PATH is overriding the command path present on your subprocess. I did not have a solution till now. If you bind your app with gunicorn in terminal then your code will also work.