Home > Database > Mysql Tutorial > How Do I Configure Django to Use MySQL?

How Do I Configure Django to Use MySQL?

Mary-Kate Olsen
Release: 2024-12-30 15:34:09
Original
643 people have browsed it

How Do I Configure Django to Use MySQL?

Configuring Django with MySQL

Connecting to MySQL

Integrating Django with MySQL is straightforward. Within the DATABASES dictionary, create an entry resembling the following:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # MySQL database engine
        'NAME': 'DB_NAME',  # Database name
        'USER': 'DB_USER',  # Database user
        'PASSWORD': 'DB_PASSWORD',  # Database password
        'HOST': 'localhost',  # Host IP or 'localhost'
        'PORT': '3306',  # Default MySQL port
    }
}
Copy after login

Alternatively, Django 1.7 allows you to utilize MySQL option files:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',  # Path to MySQL option file
        },
    }
}
Copy after login

Within the /path/to/my.cnf file, specify the same parameters as before:

[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8
Copy after login

Please note the order in which connections are established:

  1. OPTIONS
  2. NAME, USER, PASSWORD, HOST, PORT
  3. MySQL option files

Running Django Locally

For local testing, simply run:

python manage.py runserver
Copy after login

Adding the ip:port argument allows external access to your application. For production deployment, refer to the djangobook's "Deploying Django" chapter.

Database Character Set

Ensure that your database character set is UTF-8 by creating it using the following SQL:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin
Copy after login

Connector for MySQL

If using Oracle's MySQL connector for Python 3, your ENGINE line should be:

'ENGINE': 'mysql.connector.django',
Copy after login

MySQL Installation and Python Client

Install MySQL on your OS:

brew install mysql (MacOS)
Copy after login

Ensure you have the correct Python client installed (for Python 3):

pip3 install mysqlclient
Copy after login

The above is the detailed content of How Do I Configure Django to Use MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template