Skip to content

Django - Getting Started

Django: Getting Started#

Create a project#

  1. Create a virtual environment

    virtualenv -p python3.6 env source env/bin/activate

  2. Install Django

    pip install Django

  3. Create a project

    Django-admin startproject learning_site

Ensure the project name uses an underscore, because it becomes a module name

The learning_site folder:

  • is not an app but a stub
  • holds settings.py
  • holds urls.py, which defines the base URLs
  • wsgi.py is the entry point to the web server

Run the server#

cd learning_site
./manage.py runserver

Go to the link it shows you

Unapplied migrations are a way to track database schema changes

Ctrl + C to stop the server

Run Migrations#
./manage.py migrate

The database is created automatically with sqlite3, which is good for experimenting For live sites it is best to use MySQL

Hello World#

Django is different in that it uses templates and views

All views have to accept a request object

views.py:

from django.http import HttpResponse

def hello_world(request):
    return HttpResponse('Hello World')
  • Some frameworks have implicit routing by function name
  • Some functions let you set a route for a function name
  • Django URLs are created with regular expressions

To import from the current directory use from . import views

urls.py:

from django.conf.URLs import URL
from django.contrib import admin

from . import views

urlpatterns = [
    url(r'^admin/', admin.site.URLs),
    url(r'^$', views.hello_world),
]

Pluggable Apps#

  • Apps - self contained bit of functionality
  • Pluggable - Django apps that can be moved

Create an app#

It is a good idea to name the app after it’s main model

./manage.py startapp courses

__init__.py marks a directory as a module

Add courses to INSTALLED APPS in settings.py