Connecting Django with MySQL
Earlier we have created web application using Django framework where we have created normal view , render html , GET and POST method and some basic of Django form module
To connect Django with MySQL we need an interface to the popular MySQL database server that provides the Python database API.
Step 1 : Install MysqlClient
pip install mysqlclient
Building mysqlclient on Windows is very hard. But there are some binary wheels you can install easily.
Install python connector for the appropriate window
https://dev.mysql.com/downloads/connector/python/
After successful installation of connector , install mysqlclient against
- Open CMD , and start mysql
- Create a database using mysql

2. Create a table name users

Step 2: Updating the Connect String
To connect mysql with django , we will have to update the connection string in settings.py
- Locate settings.py file in your project folder
- Search for the variable
DATABASES
- Update the it with following

4. If you get the “Can’t Connect to MySQL server on ‘localhost’” . Please make sure you have started the mysql
5. After successful setup migrate table
Step 3: Migrate Tables
This below command will migrate all the default Django tables to your MySQL schema.
python manage.py migrate

If you get the error such as
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table
Then downgrade the Django to 2.0.5 and do migration
Step 3 : Creating Models in Django
- Open models.py from app folder
- Create a class User() that will inherit models

3. Open CMD and make migrations by python manage.py makemigrations <app-name>
i.e python manage.py makemigrations app

4. After migrations is successfully created, run python manage.py migrate

There are several commands which you will use to interact with migrations and Django’s handling of database schema:
migrate
, which is responsible for applying and unapplying migrations.makemigrations
, which is responsible for creating new migrations based on the changes you have made to your models.sqlmigrate
, which displays the SQL statements for a migration.showmigrations
, which lists a project’s migrations and their status.
5. Following table is created in MySQL database

6. Now we have to create a form. Create forms.py and write the following code

7. Update the views.py with following code

8. Create a html named post.html

Output
