gregor gregor - 2 years ago 125
SQL Question

Setting Django up to use MySQL

I'm wanting to move away from PHP a little ways and learn Python. In order to do web development with Python I'm going to need a framework to help with templating and other things.

I have a non-production server that I test all of web development stuff on. It is a Debian 7.1 LAMP stack that runs MariaDB instead of the common MySQL-server package.

Yesterday I installed Django and created my first project called firstweb. I have not changed any settings yet.

Here is my first big piece of confusion. In the tutorial I followed the guy installed Django, started his first project, restarted Apache, and Django just worked from then on. He went to his browser and went to the Django default page with no problems.

Me however, I have to cd into my firstweb folder and run

python runserver myip:port

And it works. No problem. But I'm wondering if it is supposed to work like this, and if this will cause problems down the line?

My second question is that I want to set it up so it uses my MySQL database. I go into my under /firstweb/firstweb and I see ENGINE and NAME but I'm not sure what to put here.

And then in the USER, PASSWORD, and HOST areas is this my database and its credentials? If I am using localhost can I just put localhost in the HOST area?

Answer Source

MySQL support is simple to add. In your DATABASES array, you will have an entry like this:

    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',

You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES array like so:

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',

You also need to create the /path/to/my.cnf file with similar settings from above

database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

With this new method of connecting in Django 1.7, it is important to know the order connections are established:

3. MySQL option files.

In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.

If you are just testing your application on your local machine, you can use

python runserver

Adding the ip:port argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook

If you are using Oracle's MySQL connector your ENGINE line should look like this:

'ENGINE': 'mysql.connector.django',
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download