Search code examples
djangodjango-viewshost

Django. how to get a host name for db


I'm trying to connect to database: in localhost I can do something like this:

db = MySQLdb.connect(host='127.0.0.1', user="root", passwd="", db="schooldb")

but in the server I want '127.0.0.1' to be a variable, unfortunately

   h = request.get_host()
   return HttpResponse(h)

gives me 127.0.0.1:8000 So my question is how to truncate port and leave only 127.0.0.1. Or may be you can suggest something better.

Thank you


Solution

  • [request.get_host()][1] gives you the server information for the request and not the database server information.

    To get database information (assuming you have only one database named default), you can do:

    >>> from django.conf import settings
    >>> settings.DATABASES['default']['HOST']
    >>> 'MyDBServer'
    >>> settings.DATABASES['default']['PORT']    
    >>> '9999'