Home >Database >Mysql Tutorial >How to Configure Django to Use MySQL?
In Python-based web development, Django offers a comprehensive framework for managing various aspects of web applications. When it comes to database management, Django provides support for MySQL. Here's how you can set up Django to work with MySQL:
To establish a connection between Django and MySQL, you'll need to modify the settings.py file located within your Django project directory. Within the DATABASES dictionary, define an entry as follows:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } }
Here, replace 'DB_NAME' with the name of your MySQL database, 'DB_USER' with the appropriate username, 'DB_PASSWORD' with the corresponding password, and 'localhost' with the IP address of your MySQL server (change it to 'localhost' if running on the same machine).
To verify the connection, you can run the following command:
python manage.py runserver
This command launches a development server that allows you to access your application from localhost by default.
If your application only works when you run 'python manage.py runserver myip:port', it may indicate that Django is not properly configured to run on a specified IP and port. Ensure that you have properly modified the ALLOWED_HOSTS setting in settings.py to allow access from your required IP and port.
Once you're ready to deploy your application, it's recommended to use a proper server configuration for production environments instead of relying on 'python manage.py runserver'. You can find detailed guidance on Django deployment in the djangobook.
MySQL's default character set may not be UTF-8. While testing on your local machine, consider creating your database using:
CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin
If you're using Oracle's MySQL connector, ensure the 'ENGINE' line in settings.py reflects the following:
'ENGINE': 'mysql.connector.django',
The above is the detailed content of How to Configure Django to Use MySQL?. For more information, please follow other related articles on the PHP Chinese website!