Django Code Snippets

Useful & Common Code Snips in Python.
Based around Django.


pip3 install django
pip3 install django==1.9


django-admin startproject Project_Name

Created Files: = Tells python this is to be treated like a package. = where SECRET_KEY is; add apps to INSTALLED_APPS. = Well point to your apps; urlpatterns for url views.

Django Webapp structure.

Start Application:

python runserver

Create New App:

python startapp APP_NAME


webapp folder = Treated as it’s own App. = For administration. = Holds the name of the App. = Database structures and metadata. = Allows you to write tests to ensure updates don’t break anything. = Controls what is served based on URL patterns (using regex). = Handles what the end-user sees and interacts with.

Django is a Model View Controller (MVC). = Model = View = Controller

You now have a Django MVC and WebApp set up, but they must be linked.

To link the webapp to the mrdj, add the “APP_NAME” to the mrdj/ file.


Update file to include the Controller of the WebApp.

Add include after url, and url(r'^webapp/', include('webapp.urls)) to the urlpatterns array.


Create a new index view for the WebApp

In the webapp/ file:

from django.http import HttpResponse
def index(request):
return HttpResponse("<h1>HEY!</h1>")

This will respond with HEY! when visiting mrdj/webapp url.

Add this new view to WebApp/

Allow this new index view to be rendered when visiting the root url for this WebApp.

from . import views
urlpatterns = [
url(r'^$', views.index, name='index')

This will import “views” which will allow python to render the index view for the webapp.
In the webapp/ file we defined a function “index” which contains the HTML for the “index” view, and in the file we are rendering that view when the url = “mjdj/webapp/” (webapp root).

Create Another New App — “personal”

New WebApp “personal”.

python startapp personal

Install App

In the mrdj/ file, add ‘personal’ to INSTALLED_APPS.


Add personal.urls Path to mrdj/

Create new for the Personal Webapp.

from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r’^webapp/’, include(‘webapp.urls’)),
url(r’^$’, views.index, name=’index’),

Update in Personal

from django.shortcuts import render
def index(request):
return render(request, ‘personal/home.html’)

Create two new folders: templates & templates/personal

Cloud9 Workspace Django on Python3

Go into the Preferences (click the gear icon in the top-right corner), then click Language Support. Change the dropdown for Python Version to Python 3. Then, enter the following commands in the terminal:
sudo rm /usr/bin/python
sudo ln -s /usr/bin/python3.4 /usr/bin/python


Like what you read? Give Rio Weber a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.