If you are a web developer, choosing a web framework to build an app is a big deal. There are quite a number of frameworks out there to pick from, each designed to meet general as well as specific requirements.
Django is an open source backend framework that focuses on one simple principle: rapid development. By following common pragmatic paradigms such as using MVC (model-view-controller) core architecture, and having its own Object Relation Mapper (ORM) to make database CRUD operation calls, Django makes it to build complicated features quickly.
Another philosophy the Django community follows is called DRY (or Don’t Repeat Yourself ) that states that you write the code in a way such that you can reuse it instead of writing too much boilerplate code in your application
In this tutorial, you will be building a small Django web application with the help of the Crowdbotics App Builder which reduces the amount of time needed to get your Django app up and running even further.
You: An app builder, what? Why?
Using an app building platform is potentially one of the best things you can do in terms of saving time and cost that goes in order to build your next product or service. The Crowdbotics App Builder greatly reduces initial setup time for Django applications.
With these steps, I do not want to convey that this is a promotional article. Those are not my intentions. I just want you to know everything I know about this app building process such that if you decide to use Crowdbotics platform as a service, you know what you are getting into.
The workflow is simple and the intention is to help solo/indie/startup and existing team to build and launch their product(s) without spending too much time in scaffolding or generating the project. Crowdbotics has multiple boilerplate ready to use projects to get you started.
In the next section, you will be building your first Web App app with Django and Crowdbotics.
To setup a Crowdbotics app, you have to visit app.crowdbotics.com and register an account. You can either login from Github or use other authentication (an email) options to create a new account. Once you are logged in you will be welcomed by the dashboard screen similar to below.
Click on the big plus sign button to create a new application and it will prompt with options of which tech stack to choose from in the next window.
Choose Django under the category web app.
Scroll down below and enter the name of the application and click the button
Create my app!.
In a matter of seconds, the app builder will generate a new application for you. You will be prompted with a dashboard interface of your project. There are so many options for you to do such as collaborating over Slack with your team members, or viewing the source code of your project on Github or requesting for a designer or developer from Crowdbotics services and so on.
The Crowdbotics App Builder generates an automatic Github repository under their host name. It also shows recent PRs and commits made on the Github repository. So take a halt and take a look at this repository. To use this scaffolded project, all you have to do is clone this repository and start working on it. There is a
README.md file attached to every project or app generated using Crowdbotics app builder that has a reference on how to get started.
Open your favorite terminal and run the below command to clone the repository.
The Github URL in your case will be different depending on the name of your web application. Once the cloning is done, traverse inside the project directory. You will get the following structure.
Take a look at the project structure.
djangowebapp_demo_1240 is your main project builder.
Pipfile and look out for the packages that are needed to install in order to run this web app. In this line, notice that our project requires you to have Python version
3.6 installed on the local dev machine.
1python_version = "3.6"
If you do not have it already, use the below command from terminal to install.
1pipenv --python 3.6
Also run the below command, to install all dependencies described in
In the previous section, you looked into the project structure made available to us by Crowdbotics App Builder. Now, take a look at the file called
settings.py. You will notice many different settings such as
DEBUG mode, application definitions, middlewares, database setting, setting up Timezone or enabling/disabling Internationalization.
1DEBUG = True23ALLOWED_HOSTS = 456# Application definition78INSTALLED_APPS = [9 'django.contrib.admin',10 'django.contrib.auth',11 'django.contrib.contenttypes',12 'django.contrib.sessions',13 'django.contrib.messages',14 'django.contrib.staticfiles',15 'django.contrib.sites'16]1718MIDDLEWARE = [19 'django.middleware.security.SecurityMiddleware',20 'django.contrib.sessions.middleware.SessionMiddleware',21 'django.middleware.common.CommonMiddleware',22 'django.middleware.csrf.CsrfViewMiddleware',23 'django.contrib.auth.middleware.AuthenticationMiddleware',24 'django.contrib.messages.middleware.MessageMiddleware',25 'django.middleware.clickjacking.XFrameOptionsMiddleware',26]272829# Internationalization30# https://docs.djangoproject.com/en/1.11/topics/i18n/3132LANGUAGE_CODE = 'en-us'3334TIME_ZONE = 'UTC'3536USE_I18N = True3738USE_L10N = True3940USE_TZ = True
There are many other settings, but we are not going to look at them in detail here. The main concern in this section is to get familiarize with the concept of
App Definitions. Django comes pre-installed with some default apps such as authentication and session manager apps. An app in Django is known as a self-contained unit of code which can be executed on its own. Take a look at the section
INSTALLED_APP in the above file.
Each app can operate different functionalities such as serving a webpage to the browser or handle user authentication, handle user session and so on. Any apps you create or install a third-party, has to be added and mentioned in this section.
To verify that a Django project works, run the following command.
1python manage.py runserver
If the above command successfully runs, you will see a similar output below.
1Performing system checks...23System check identified no issues (0 silenced).45You have unapplied migrations; your app may not work properly until they are applied.6Run 'python manage.py migrate' to apply them.78Django version 1.11, using settings 'mysite.settings'9Starting development server at http://127.0.0.1:8000/10Quit the server with CONTROL-C.
Django server always run at
http://127.0.0.1:8000/ unless you want to change the the port. Using the development server you can create your app rapidly and test it well before deploying on the production.
To create our first Django app run the following command from a terminal window.
1python manage.py startapp helloworldapp
Django comes with the utility that automatically generates the basic directory structure of an app. All you have to focus is on writing the code rather than creating files and folders. Using
manage.py command, the newly created Django is created as a top level module in the directory structure rather than a sub module.
The directory structure of the
helloworldapp will be similar to below.
1helloworldapp/2 __init__.py3 admin.py4 apps.py5 migrations/6 __init__.py7 models.py8 tests.py9 views.py
To get Django to recognize the newly created app, open
settings.py file and add the name of your app under
1# Application definition23INSTALLED_APPS = [4 'django.contrib.admin',5 'django.contrib.auth',6 'django.contrib.contenttypes',7 'django.contrib.sessions',8 'django.contrib.messages',9 'django.contrib.staticfiles',10 'django.contrib.sites',11 'helloworldapp'12]
Now run the development server and visit the URL
http://127.0.0.1:8000/ in the browser. When the page loads, you will get the warning that you have unfulfilled migrations. Migrations in a Django app, help you change the database schema without losing any previous data. Whenever a new database model is created, running migrations will update the existing database tables to use the new schema without you having to lose any data. Migrations also help you to avoid going through the process of dropping and recreating the whole database yourself.
To use migrations in our application, run the following command.
1python manage.py migrate
If the command runs successfully, you will see a similar output like below.
1Operations to perform:2 Apply all migrations: sessions, auth, contenttypes, admin3Running migrations:4 Rendering model states... DONE5 Applying contenttypes.0001_initial... OK6 Applying auth.0001_initial... OK7 Applying admin.0001_initial... OK8 Applying admin.0002_logentry_remove_auto_add... OK9 Applying contenttypes.0002_remove_content_type_name... OK10 Applying auth.0002_alter_permission_name_max_length... OK11 Applying auth.0003_alter_user_email_max_length... OK12 Applying auth.0004_alter_user_username_opts... OK13 Applying auth.0005_alter_user_last_login_null... OK14 Applying auth.0006_require_contenttypes_0002... OK15 Applying auth.0007_alter_validators_add_error_messages... OK16 Applying sessions.0001_initial... OK
Try running the development server again and visit the local host URL again, you are not going to see any warnings this time.
You will have to create templates in the
helloworldapp directory to avoid errors in the future. Use the following terminal commands and create new folder
templates and inside it a new file called
index.html which is going to be our first view.
1cd helloworldapp2mkdir templates3touch index.html
Next, open the
index.html file and the following snippet.
1<html>2 <head>3 <title>Home Page</title>4 </head>5 <body>6 Hello world7 </body>8</html>
This page will still not render as you haven’t configured the views and let the Django app know about the new view to render. To configure views, go to the
helloworldapp directory and inside it, open file
views.py. Add the following content.
1from __future__ import unicode literals2from django.shortcuts import render3from django.views.generic import TemplateView45class HomeView(TemplateView):6 template_name= 'index.html'
A view in Django app determines what to display on a given route. In the above file, you are telling the Django app to render the HTML file
index.html. However, this will not work. We still need to setup a route and map it to this view.
To map the route to our view, open a file called
djangowebapp-demo-1240/djangowebapp_demo_1240. It consists of the following code.
1"""djangowebapp_demo_1240 URL Configuration2The `urlpatterns` list routes URLs to views. For more information please see:3 https://docs.djangoproject.com/en/1.11/topics/http/urls/4Examples:5Function views6 1. Add an import: from my_app import views7 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')8Class-based views9 1. Add an import: from other_app.views import Home10 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')11Including another URLconf12 1. Import the include() function: from django.conf.urls import url, include, include13 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))14"""15from django.conf.urls import url, include16from django.contrib import admin1718urlpatterns = [19 url('', include('home.urls')),20 url(r'^accounts/', include('allauth.urls')),21 url(r'^api/v1/', include('home.api.v1.urls')),22 url(r'^admin/', admin.site.urls),23]
Modify this file accordingly.
1rom django.conf.urls import url, include2from django.contrib import admin3from helloworldapp.views import HomeView45url patterns = [6 url(r'^$', HomeView.as_view()),7 url(r'^accounts/', include('allauth.urls')),8 url(r'^api/v1/', include('home.api.v1.urls')),9 url(r'^admin/', admin.site.urls),10]
Now go back to the root directory and run the development server with the following command.
1python manage.py runserver
In the browser window, you will notice the following result.
This is just a start.
If you are already a Django expert, I urge you to take a look at this process of building the application that saves a lot of time.