Django connects to a MySQL database and makes calls to it.
To connect and interact with a MySQL database in Django, you need to perform the following steps:
- Install Django and the MySQL client library.
- Install Django with the mysqlclient option using pip.
- Configure the database connection in the settings.py file of the Django project.
- DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘your_database_name’,
‘USER’: ‘your_username’,
‘PASSWORD’: ‘your_password’,
‘HOST’: ‘your_host’,
‘PORT’: ‘your_port’,
}
} - Replace ‘your_database_name’, ‘your_username’, ‘your_password’, ‘your_host’, and ‘your_port’ with the correct values based on your actual situation.
- Define database models in the models.py file of a Django project.
- Import models from the Django framework and create a class called YourModel that inherits from models.Model. Define two model fields, field1 as a CharField with a max length of 100 characters and field2 as an IntegerField. The __str__ method will return the value of field1 when called.
- This is an example model that you can customize by defining your own model fields as needed.
- Perform a database migration to create the necessary tables.
- Generate migration files with Python using ‘makemigrations’ command, then apply those migrations using ‘migrate’ command.
- Write view functions in the views.py file of the Django project to make database calls.
- import the necessary modules
from the models file, import YourModelcreate a function called your_view that takes in a request
fetch all data from the database
render the data in the template
return the rendered template with the data - This is a simple example that you can use to write your own view functions as needed.
- Create a template named your_template.html to display the data retrieved from the database.
-
Database Data:
-
{% for item in data %}
- {{ item }}
{% endfor %}
- This is a basic example template that you can customize as needed.
- Configure URL routing in the urls.py file of a Django project.
- Import the ‘path’ function from the Django URLs module and then define a URL pattern that links to a specific view function.
- Replace ‘your-url/’ with the actual URL you want.
- Run the Django development server:
- start the server by running the command “python manage.py runserver”
When you access the configured URL now, Django will connect to the MySQL database and call the corresponding view function to retrieve data and render it on the template.