1.

How can you set up a Database in Django?

Answer»

Django is set up to communicate with SQlite a lightweight relational database. By DEFAULT Django automatically creates an SQLite database. Django also supports PostgreSQL, MySQL, and Oracle. 

Along with configuring Django to connect to a database you need to install the required Python packages to communicate with the database.

To connect to the database, Django configuration is done inside settings.py file of Django project in the DATABASES variable.

We will go step by step as follow to set up MySQL - 

1) First Install MySQL Database Connector :   

SUDO apt-get install libmysqlclient-dev

2) Then Install the mysqlclient library using the following COMMAND :

PIP install mysqlclient

3) Now Install MySQL server :

sudo apt-get install mysql-server

4) Create the Database :

i) First, verify that the MySQL service is running:

systemctl status mysql.service

ii) Log in with MySQL credentials using the following command where -u flag for declaring your username and -p flag that tells MySQL that this user requires a password :  

mysql -u db_user -p

iii)  Create a database

CREATE DATABASE db_name;

iv) Exit MySQL server, press 

CTRL + D

5) Now add the MySQL Database Connection to Application:

    i) Now edit the CONFIG file so that it has MySQL credentials. We will use vi to edit the file and add the following information:

       sudo vi /etc/mysql/my.cnf       database = db_name         user = db_user         password = db_password         default-character-set = utf8

ii) Go to the settings.py file. Replace the current DATABASES lines with the following:

      # Database         # https://docs.djangoproject.com/en/2.0/ref/settings/#databases         DATABASES = {             'default': {                 'ENGINE': 'django.db.backends.mysql',                 'OPTIONS': {                     'read_default_file': '/etc/mysql/my.cnf',                 },              }

i) Go to the settings.py file. Replace the current DATABASES lines with the following:

  # Database         # https://docs.djangoproject.com/en/2.0/ref/settings/#databases         DATABASES = { 'default': {               'ENGINE': 'django.db.backends.mysql',           'NAME': 'djangoApp',   'USER':'root',          'PASSWORD':'mysql',           'HOST':'localhost',         'PORT':'3306'                 },             }

6) After file edit, need to restart MySQL for the changes to take effect :

    systemctl daemon-reload     systemctl restart MySQL

7) Now Test MySQL Connection to Application:

python manage.py runserver your-server-ip:8000


Discussion

No Comment Found