Creating a project in Django

Last time we went over how Django works and how a project is divided into the MVT layers. Now for this blog I will talk about how to start and create a project using Django.

Initialization

Most of the commands to create and initialize parts of the project will be in the command prompt. We can start out by first installing Django using the pip to install Django

By typing “pip install django” in the command prompt you can install Django into your python library.
 Note here that the pip is the package manager for Python and comes automatically with Python 2.8 or Python 3.4 and greater. If you have an older python version you will have to set up pip manually.

Once Django has been installed you can enter whatever folder you want the project to be in and open a command prompt to that folder. Type in “Django-admin startproject <project name>” creates a Django project for you in that folder based whatever name you gave it.

When created the project structure should look something like this:
 project
 | — project
 | | — __init__.py
 | | — settings.py
 | | — urls.py
 | | — wsgi.py
 | — manage.py

These files will help you set up the workings of your project.
 Note here the __init__.py file is nothing special, it’s just a file for python to understand that this file is a package.

We will need apps for our project as apps will provide the functionality for the project. Executing the “python manage.py startapp <app name>” will create a new folder inside your project.

Your project’s structure should look something like this:
 project
 | — app
 | | — migrations
 | | — __init__.py
 | | — admin.py
 | | — apps.py
 | | — models.py
 | | — tests.py
 | | — views.py
 | — project
 | | — __init__.py
 | | — settings.py
 | | — urls.py
 | | — wsgi.py
 | — manage.py

Now before our app is completely initialized we will need to modify the settings.py file. This file handles all the settings of our project such as installed apps, databases, static files, language and time.

All we need to do is modify the “installed apps” section to add our newly created app to the list so Django recognizes our new app.

The above picture showcases what your installed_apps section should look like after you have added your app’s name to the list for which in this case I called my new app “app”.

With that done you can test your project using the “python manage.py runserver” command. This makes it so we can view the project onto a browser by going to http://127.0.0.1:8000 (this can work if you substitute the ip with “localhost”). When you do this you should be popped into a screen that says “It works!” nothing happens here so you can close the browser and turn off the server using Control + c.

Models

We can start off by creating the models. Creating models in Django will somewhat feel the same when you create tables in SQL. So lets go into the models.py folder in the newly created app’s folder and create a simple model that will take in a subject and a date.

The above is just a simple model that takes in a subject of 255 characters and a DateField that sets the default date to the current date. We also define an inner class called Meta. This class is used by Django to provide extra information for a model. Django has a great deal of logic under the hood to adapt it’s behavior based on what information is in the Meta class. In this case we define how the admin panel will refer to our model in a pluralized version and how it will order each new Topic object by date.

Next we need to update the database to reflect the new state of the code. Note here that you should let Django do all the database calls as it can’t track manual changes to the database like dropping a table manually will break your application. Using the commands “python manage.py makemigrations <app name>” and “python manage.py migrate” creates and executes the database script to match changes to the model classes. Another note Django’s default database use is SQLite and it’s just a file in your project folder. If you want to use other databases like MySQL or PostgreSQL you will have to do some changes to the settings.py file and download the drivers for python.

Before we move on I’ll briefly explain the admin panel. The admin panel is a place where you can customize and interact with your models. To access the admin panel we first need a superuser and to create it we simple execute this command “python manage.py createsuperuser” it will then ask you for credentials for the user. Next we go to the admin.py file in your app’s folder. This file will help shape how the admin panel will associate the new model.

The fieldsets just defines input values for our model under a header called “Information”. Next we have a list_display attribute, this is so the admin panel will display a list with whatever attributes of the model you wish to display. Next we have list_filter this will create a filter for the model and search_fields will create an search text field.

Above pictures shows what our model will look like in the admin panel. I have outlined in red the search field and filter because if we have not specified them they would not appeared. Also if we didn’t specify the list_display the many objects will just appear as “TopicObject”.

Views

Next we have the views. When creating the views it’s best to think of them as the controller. They control and manage what will be displayed onto the html file. We are just going to keep it simple and make a home page to view links. We will also make it so we can input new Topics for our Topic model.

First we create the form. The form is a way to insert data in form fields and when submitted will be processed and added to the database. We will need to manually create a forms.py file in the app folder and edit it.

The above shows a simple form that will take in a subject field. We already set the default date in the Topic model class so there is no need for a date field. Now we can go on to the views.py file.

In order to set this view up correctly, we need to specify a few attributes at the beginning: the template to be rendered, the model we are using, the form class to be used to handle the data from the POST request, the URL we need to redirect the user to on a successful submit and the success message. We have a get and post who’s primary purpose is to set and obtain the form information. And finally we have the form_valid method which validates the form and saves changes to the object being changed in the database.

Before we get to the template we need to set up the urls for the project. For that we will need to set up the ursl.py file in your project folder(it should be where settings.py was).

In here we tie the new view to a URL. There are many ways of doing this but this is the simplest I was able to learn.

Template

All templates inherit from a base one. This provides the HTML structure for all others, in a very OOP type of fashion. It also specifies blocks, which are areas that can be overridden by children so they can provide custom content for those areas. The templates are mostly html pages with a mix of Django’s template language.

The above picture is a base.html file located in the app/template/app folder(This was created manually). You will need to specify your templates like this so Django may not confuse a base.html in another app.
 The static tag so that we can get easy access to the static path without hardcoding it in the template by using {% static … %}. The code in the special {% … %} sections is code that defines logic. The code in the special {{ … }} represents variables that will be rendered on the page.

This will be our template for our TopicHomeView. We extend the base.html and override the page-content block with what we want to show on the page. We use the template language to create an if statement to check for success messages and show them. We then create a form by using the form.as_p which renders our form automatically. This sets all the necessary fields for us. Note the csrf_token, this is rendered into a token by Django and will become part of the data sent to the server on submission.

When we run the server and go to localhost:8000/home we will see that our new page is working perfectly.

Conclusion

That is a walkthrough of a simple way to use Django and it’s functionalities. Of course this isn’t all Django has to offer and there are plenty more to learn. You can always check on django’s website for their documentation. They provide explanations and examples of the many modules in Django. As you work more with Django you will find trends and adapt them or piece them together to create even bigger applications. This concludes the walkthrough for Django and next time I will go on over to Lua.

Show your support

Clapping shows how much you appreciated Brian Cruz’s story.