Setting Django up to use MySQL
You have decided to create a Python web development project using the Django framework and want to connect it to your MySQL database. Here's a step-by-step guide to help you do just that:
1. Setting Up MySQL Support
To use MySQL with Django, you need to specify database-related settings in your Django project. Navigate to your project's settings.py file and locate the DATABASES dictionary. Add the following code within the default configuration block:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'localhost', 'PORT': '3306', } }
Replace 'DB_NAME' with the name of your MySQL database, 'DB_USER' with the username for accessing the database, 'DB_PASSWORD' with the corresponding password, and 'HOST' with the IP address or hostname of the MySQL server.
2. Running Django Locally
During development, you can test your Django application by running the following command:
python manage.py runserver
This command starts a development server on your local machine, accessible only to localhost. For testing purposes, it is convenient, but for production deployment, see the Django documentation.
3. Utilizing MySQL Option Files
An alternative approach to setting up MySQL support is to use MySQL option files. In the DATABASES dictionary, include the following:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '/path/to/my.cnf', }, } }
Create a MySQL option file at '/path/to/my.cnf' containing the following settings:
[client] database = DB_NAME host = localhost user = DB_USER password = DB_PASSWORD default-character-set = utf8
4. Specific Considerations
a. Character Set: Ensure your MySQL database has a UTF-8 character set by creating it with the following SQL statement:
CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin
b. Oracle's MySQL Connector: If you're using this connector for Python 3, adjust the 'ENGINE' line in settings.py to:
'ENGINE': 'mysql.connector.django',
c. Installation: Install the MySQL package for your OS (e.g., 'brew install mysql' for macOS).
d. Python 3 Database Client: Use 'pip3 install mysqlclient' to install the MySQL client package for Python 3.
The above is the detailed content of How to Configure Django to Connect to a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!