How to Connect MySQL Database with Django Project
To connect MySQL database with a Django project, follow these steps:
-
Install the necessary dependencies: Make sure you have the MySQL database driver for Python installed. You can do this using pip:
pip install mysqlclient
-
Configure the database settings in your Django project's
settings.py
file: Add the following lines to yoursettings.py
file:DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'your_database_name', 'USER': 'your_mysql_username', 'PASSWORD': 'your_mysql_password', 'HOST': 'localhost', 'PORT': '', } }
Make sure to replace
your_database_name
,your_mysql_username
, andyour_mysql_password
with the actual values for your MySQL database. -
Run migrations: Run the following command to create the necessary tables in your MySQL database:
python manage.py migrate
This will create all the necessary tables and relationships defined in your Django models.
-
Test the connection: To test the connection, start the development server using the following command:
python manage.py runserver
If there are no errors, you should be able to access your Django application at http://127.0.0.1:8000/ in your web browser.
That's it! You have successfully connected your Django project with a MySQL database.