# How to build a Django App - Part 3: Creating the database

This article covers how to set up a database and admin panel for a Django site. This section is arguably the most complicated part of the tutorial, but it is integral that this done correctly as it provides the backbone to our project.

To start, we need to go to settings.py and scroll through the file until we see databases. It will look like this.

DATABASES = [    ‘Default’ : {        ‘ENGINE’ : ‘django.db.backends.sqlite3’),        ‘NAME’ : os.path.join(BASE_DIR, ‘db.sqlite3’),    }]

We can see that by default it uses sqlite. This is a simple file-based database. It’s really good for prototyping and development but ideally, you wouldn’t use it in production. Instead, we’re going to use mysql. In order to do this, first, we need to install mysql. If you already have mysql installed, you can skip this part.

To install mysql, open another terminal and run the following command. To avoid confusion we will refer to this one as the SQL terminal.

$sudo apt-get update Then once the system is up-to-date enter the following command. $ sudo apt-get install mysql server

You will be asked to set a password for the root user. This isn’t necessary but probably worth doing. Once the installation is complete, we can run the next command to see if it’s running.

$service mysql status Once we’ve checked that it’s running, we need to install the Python mysql module. $ sudo apt-get install python-mysqldb

Now that we’ve done that, we can go ahead and create our database. First of all, we need to run the following command to log into mysql.

$sudo mysql -u root -p If you decided to set a password earlier, you will be asked to enter it. Once you have done that, you will be logged in. You will know this because the server will now have mysql> on the left. Now we can actually create the database using SQL. Enter the following syntax to create a todolist database. > CREATE DATABASE todolist; To check the database has been successfully created, we can enter the following to see all of the databases we have. > SHOW DATABASES; So, now that we have created the database, we need to go back to our settings.py file and edit the DATABASES code from before. Edit the code so it looks like the this. DATABASES = [ ‘Default’ : { ‘ENGINE’ : ‘django.db.backends.mysql’), ‘NAME’ : ‘todolist’, ‘USER’ : ‘root’, ‘PASSWORD’ : ‘12345678’, ‘HOST’ : ‘’, ‘PORT’ : ‘’, }] For PASSWORD, be sure to specify the actual password you used. HOST is blank as the default is your localhost and PORT is also blank for the default port. Once you have done this, make sure to save it. Now we want to run our migration. This next command is going to create all the tables we need for our app. Go back to the terminal and start by entering the following command. $ python manage.py migrate

You should see that it has applied those migrations. Now go back to the SQL terminal and enter the following command.

> use todolist;

Then to view our tables, enter:

> show tables;

You will now a bunch of table names appear. This means our tables have been created successfully.

The next thing we want to do is create our model for todos. In the text editor, go to the todos folder and then open models.py. Inside this file, we want to create a class for our models. Type the following code into the editor.

class ToDo(models.Model):    title = models.CharField(max_length=200)    text = models.TextField()    created_at = models.DateTimeField(default=datetime.now, blank=True)

CharField needs to have a max length for the characters. Having a max length ensures that more correct data is entering the database. You can just set this to the maximum limit it will allow but this isn’t best practice. TextField is very similar but deals with larger amounts of text, such as blog posts.

We want our date and time to be automatically inserted. To do this, we can install a Python package called datetime. Add the following import statement at the top of the file, below the first import statement.

from datetime import datetime

That’s all we need to do to this file for now. Go ahead and save it and then navigate to settings.py again and add the following line of code to INSTALLED APPS.

‘todos.apps.TodosConfig’,

The chunk of code should now look like this.

INSTALLED_APPS = [    'todo.apps.Todoconfig',    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',]

Now go back to the terminal. We’re going to run a migration by entering the following command.

$python manage.py makemigrations todo If you get a warning that says your URL pattern uses include with a regex ending with a $, you can go and comment that line of code out in the urls.py file for now and then run the migration again.

Once you have entered the command you should see that it has created a migration. It should give you something like this.

todo/migrations/0001_initial.py

Now, enter the following command.

$python manage.py sqlmigrate todo 0001 That will create our model. Now we need to run: $ python manage.py migrate

Now, go to the SQL terminal and show the tables once again. You will now see a new table called todos_todo.

Next, we are going to create a user. This will allow us to use the admin panel. Enter the following command into the terminal.

$python manage.py create superuser --username=sam --email=notarealaccount@spam.com You can choose whatever name you like for username. Once you have entered this, you will be asked to enter a password. Be sure to choose something complex as it might be quite picky about what you can have as your password. Now, we should be able to log into the backend. To do this, we first need to run the server. Run the following command to start the server. $ python manage.py runserver

Now, go to the search bar in your browser and enter localhost:8000/admin. You should be given a page asking you to log in. Enter the username and password you just set and you should then be greeted with a page like this.

This is the admin page. From here we can add more users and groups. We can also add users to groups and set permissions for those groups. All of this serves as great functionality that comes out of the box, meaning we won’t need to add this stuff later if necessary.

You might have noticed we don’t have todos anywhere. To add this, we need to go to todos and then admin.py. In this file, we first need to import Todo from models. We can do this by adding the following import statement.

from .models import Todo

Now, we just need to add one more line of code to the file. Type the following code a couple lines below the two import statements you should now have in the file.

admin.site.register(Todo)

Save the file and refresh the webpage. You should now see a "Todos" section in the admin panel, like so.

Let’s go ahead and add a To-do. You can call it whatever you want but I have simply chosen Todo One. In the text box, I have just said that this is my first todo for this application. Below the text box, you will notice that it has a date field and a time field. Thanks to the code we added to our Todo class, this should be current date and time. If everything is correct, you can go ahead and click the “SAVE” button. You should then be given a page like this.

From this, we can see that our “object” was successfully added. This is good but really, we want it to give us the title, rather than “Todo object”. In order to do this, we need to go to our models.py file and add the following code to our class.

def __str__(self):    return self.title

The entire file should now look like this.

from django.db import modelsfrom datetime import datetimeclass Todo(models.Model):    title = models.CharField(max_length=200)    text = models.TextField()    created_at = models.DateTimeField(default=datetime.now, blank=True)    def __str__(self):        return self.title

Save the file and refresh your browser. You will now see the title rather than “object”. Now, let’s add another one. Again, for simplicity, I’m just going to call this one “Todo Two”. Once you have entered in the information and clicked “SAVE”, you will see that a second To-do has been added.

### Back-end complete

At this point, we now have a fully functioning back-end, meaning we can start working on the front-end of our website. In part four we will begin working with HTML to create a simple interface for our users to interact with.