Django is a scalable and open-source Python web framework for building custom web applications. It was built to be fast and flexible on a variant of the MVC pattern called Model-View-Template. It has many features built in like an admin dashboard, user authentication, and form validation.
It is used on many popular large-scale platforms like Instagram and Pinterest. The projects are made up of several apps which are self-contained and can be removed and used in other projects.
Another Python framework it is often compared to is Flask. The main differences between Django and Flask are that Django is very structured and it must be used in the Django way. Flask offers much more flexibility. The current major version of Django is 2.0.
In this post, we use Django with the Django Rest Framework to build an API, also known as an application programming interface. This project is built and maintained separately from the main Django project. The API is used as the data source for the project I am posting using a React front end for a portfolio template. The framework is relatively straight-forward to understand and to get started with.
Specifically, the API’s database will hold information on project and blog post data. There is also a section on services which can be added, but I’ve decided to hard code that for now since it will not likely be changed often.
The steps to follow are:
- Create the models in Django as usual.
- Serialize the objects using the Django REST framework and create a view to access the data.
- Upload the API to a server.
The Django REST API
So, what is a REST API? REST stands for REpresentational State Transfer. API stands for Application Programming Interface, as mentioned before. This signifies that there is an interface to access the data in the application. This comes in the form of a URL.
It is generally created to allow external entities access to data so that this data can be used to build separate applications. A well-known example is the Twitter API where you can access tweets through a Twitter developer account.
They are often serialized in the form of JSON data which can be accessed through HTTP requests like GET, POST, PUT and DELETE. A GET request fetches data from the server. POST and PUT can both create data on the server. POST can create new data points while PUT is meant to update the data only. DELETE removes data.
Benefits of using a REST API
The beauty of this decoupled structure is that it makes maintenance a breeze. Especially if you want to rebuild the front-end, nothing on the database needs to be retouched. Similarly, another back-end in Spring or Node.js, for instance, can be added on without affecting the front-end code.
Another benefit is that the same back-end can be used with multiple front-ends to create different user experiences such as one for mobile, desktop and another one for wearables.
Start the Project
First, install django.
conda install django works if you have anaconda installed.
make sure you have Django and the Django REST Framework installed.
pip install djangorestframework should do the trick. It doesn’t seem to be available through
conda the package manager for Anaconda. This can be confirmed with
conda search djangorestframework.
Now, navigate to the folder where you want to create the API. In my case, I navigate to my dev folder on my desktop with
Create a virtual environment
An additional step that might be desired here is to use a virtual environment. This comes in handy when getting the
requirements.txt if deploying to Heroku.
Create the project
Next, start the project with the following command, where
portfolio_site_api is a name you can choose. Note that underscores work here for the name of the project but not dashes.
Open the project in an editor of your choice. Here I am using Visual Studio Code. The generated files are shown below. The folder contains an inner configuration folder of the same name as the project and a
Within the internal folder are the
settings.py and the
urls.py file. The
settings.py file has configuration information that we have to edit.
urls.py is where we can do URL routing for views. Right now it only contains a path to the admin panel. We will see this later when we create a superuser.
In order to use the Django REST framework in our project, we need to modify the
setting.py file. Add
'rest_framework' to the end of the list as shown below.
Create the App
This app refers to the internal self-contained apps of the project, not the whole application. This can be confusing. Here, we will create 1 app and add in models for the blog posts and for the portfolio projects.
The Portfolio Site App
To do this, type the following command where
portfolioapp is the name of the app.
manage.py in the command refers to the
manage.py file in the main project folder, thus this command should be run from the
portfolio_site_api directory for it to work. Hence, run
cd portfolio_site_api/ to move into that folder first.
A folder with the app should now be available. The
migrations folder will contain the schema to create the SQLite database once the model has been defined.
admin.py is where the models are registered.
models.py is where the models are defined.
tests.py is where you can run unit tests.
Add the name of the application you just made in the settings file.
Create the Models
We will be creating a model which contains data on each post such as the title, author, content, date created, date updated, category, image, and a slug. The next model will contain data on projects such as the title, author, and description.
To do this, open the
models.py file and add in the code which follows.
The general format for defining a field in the database is
models.CharField(max_length=100). So, start with
models. and call the function to create the desired field, with the appropriate parameters. There are quite a few to choose from like
Note that some of the parameters may be required or an error will result. For example,
the max_length parameter is required for the
CharField as shown below.
In other cases, they are optional as below.
auto_now = True means that the field will take on the time that the resource was created.
The Django Model field reference is a great way to browse the different fields and parameters and choose the one which is needed.
The unique id for each field appears automatically as an
AutoField so there is no need to include one manually. This is set as the primary key of the table. For the
Post model schema (this will be generated after migrations are performed) this appears as below:
Displaying entry names in the Admin Panel
Without the function below the model classes (reproduced below), the names of the entries into the database will show up as generic objects of the model object type in the admin panel (the admin panel will be initialized later on). For a
Post object, for example, the first object will appear as
Post object (1).
In Python 3 you use the function below to prevent this from happening. In Python 2 use
unicode instead of
Register the Models
Now we have to go to the
admin.py file in the
portfolioapp folder and register the models. To do this first import the models with
from .models import Post, Project then use the syntax
admin.site.register(Post) to register the models where
Post is the name of the model used in
models.py to write the model class.
Migrate the Models and Create the Tables
Notice that there are no database files in the project yet. There is no database schema or any tables yet either. This will change with this step. An SQLite database will be generated.
In order to generate these first we run
python manage.py makemigrations as below.
Looking at the file structure will show the addition of 2 new files,
0001_initial.py in the migrations folder and
db.sqlite3 (currently empty) in the project directory.
0001_initial.py generated the code to create the database tables. These are shown below.
To execute this code run
python manage.py migrate.
Checking the size of the
db.sqlite3 shows it contains content.
Create a Superuser
We can now create a superuser with
python manage.py createsuperuser. This gives us access to the admin panel which we will need later on for creating, updating and editing our posts and projects. This will require a username and a password.
The tables from the previous step need to be created before this step can work. I’m using
3ln as the username and
tortellini for the password. I left the email blank.
Login to the Admin Panel
Run the Server
In order to log into the admin panel and add in posts and projects, run the development server with
python manage.py runserver. Then, go to the URL in the output
The page below confirms that the app is working. This might look different if the version is not Django 2.0.
To go to the admin panel and append
admin to the URL like so:
http://127.0.0.1:8000/. The login page should pop up in the browser. Put in the username:3ln and password:tortellini.
Now, the admin panel should appear as below. If the credentials are not correct an error message should appear. The models we created are in the
To add data to the database, click
Add for the appropriate object type. For instance, when adding a post the following screen appears. The fields and interface were all auto-created. Great!
Now, we will add some dummy data for 3 posts and 3 projects. This data will be pulled into the React front-end for testing, so if you want to test the layout for more data/multiple rows, more data should probably be added. I’m filling in data for a hypothetical artist/photographer named Alex.
The filler text is generated from https://www.lipsum.com/. This is great for styling text and getting a feel for what the data will look like before it exists. There are more interesting versions available to try. There are also add-on generators for Visual Studio Code and Atom if those are your preferred editors.
The images I am using come from Pixabay. The links are given in the table. After the first object is added an assets folder will appear in the directory root. It carries the same path as the one which was specified when creating the database model for the ImageField. The images for the posts go to
assets/images/posts and those for projects are in
assets/images/projects. See the end of this section for the filled folders.
A really nice feature of these forms is that error messages specific to the fields are built-in and do not have to be manually created.
|Removing Backgrounds in PhotoShop||Alex||Lorem...||today, now||Editing||removing-backgrounds-in-photoshop||https://bit.ly/2udc35u|
|Adding Dramatic Lighting Effects in LightSpace||Alex||Lorem...||today, now||Editing||adding-dramatic-lighting-effects-in-lightSpace||https://bit.ly/2G2J3id|
|Abstract Art Texture Techniques||Alex||Lorem...||today, now||Abstract Art Techniques||abstract-art-texture-techniques||https://bit.ly/2GegmlP|
The post list in the admin panel is shown below after all the entries are made.
|Nature Trip to The Deep White North||Alex||Lorem...||today, now||Photography||https://bit.ly/2HWrBMO|
|Safari Collection||Alex||Lorem...||today, now||Photography||https://bit.ly/2G2J3id|
|City Scape Series||Alex||Lorem...||today, now||Art||https://bit.ly/2GegmlP|
The projects list in the admin panel is shown below after all the entries are made.
The assets folder which holds all the images:
Create the REST API
Some additional steps are now needed to create the API. The data has to be serialized and converted into JSON, then views for that data and the HTTP endpoints are needed as well as a URL to navigate to the view.
To create the serializers, make a new file
serializers.py in the
portfolioapp directory. The code to import the serializers and the models is shown below. Then, create 2 serializer classes, one corresponding to each model. The structure of each class is similar, with an inner
Meta class which specifies the model to reference and the fields to turn into JSON. According to the Django documentation, Meta classes are how you can give a class metadata.
The particular fields can be specified with
fields = ('title', 'author', 'content') or all can be used as below.
views.py file should look as shown below. There’s a few imports needed, including the model and the serializers. The 2 serializers have to be returned in the response to generate the JSON data. In this case, we only implement a GET method. For the other HTTP requests to function, they need to be defined.
Now we have to wire up the view to a URL. To start, import the view we just created with
from portfolioapp import views. In this case, I choose
The Browser View
Navigate to the view in the browser using
The full data that was generated is below:
This concludes this part of the series on building the REST API. In this post, we looked at how to create a Django REST API. We covered defining and registering the models to migrate and create the tables in the database. We created a superuser and logged into the admin panel to input data points. Finally, we created the REST API by serializing the data and representing the data in a view.
In the next part, we consume the data to populate the front-end.