Django

Getting started

django-admin startproject <project_name>

This sets up the project it generates a directory with as <project_name> which has within it.

a manage.py file and a sub-folder also called /<project_name> the subfolder has the following files:

  • settings.py
    • top level customisable project settings that are configured for a given project
  • urls.py
    • traffic management file, directs the url patterns to given pages
    • user provides a url and we provide a view
    • link to the views file with
      • from . import views and
      • a url pattern views.<function_name>

Create the file

  • views.py and then
    • from django.http import HttpResponse
    • from django.shortcuts import render (to render an html page rather than a response)
    • Use Python within your html action="using {% %}"
  • wsgi.py
    • top level settings, not really ever needed to change this.

Within the top level project folder we should have a templates folder to hold the html pages, if this isn't automatically generated by the startproject then this should be created and added as a location in the settings file under TEMPLATES = [ { ... 'DIRS': ['templates'],... of settings.py.

Some basics

Django uses objects, by convention and necessarily the objects begin with a capital. For example a table should be called People

manage.py

The manage.py file is for admin things, don't change the code in this file, it is used to manage the server with

$ python manage.py runserver

This starts the development server and can be seen in a browser at 127.0.0.1:8000 or localhost:8000 and generates a db.sqlite3 databaste (and a __pycache__ folder)

The file manage.py manages the tables and updates when there are changes with

$ python manage.py makemigrations
$ python manage.py migrate

Example with two tables; Dataset and DataFile

Call all DataFile objects related to a given Dataset

>>> ds = Dataset.objects.first()
>>> datafiles = ds.datafile_set.all()

Reversing this operation

>>> f = DataFile.objects.first()
>>> ds = f.dataset


Some other useful commands

>>> from django.db.models import Count, Min, Sum, Avg
>>> Dataset.objects.aggregate(oldest=Min('datafile__start_time')) {'oldest': datetime.datetime(2005, 12, 1, 0, 0, tzinfo=<UTC>)}

Apps

Create an app by:

python manage.py startapp apps-name

It is good practice to make a new app for each different thing, this means they can be re-used by other Django apps

Creates a directory apps-name with

  • /migrations
  • admin.py
  • apps.py
  • models.py
  • tests.py
  • views.py
  • Within each app create a new templates directory with a subdirectory named after the app, store pages here

Making an app:

  1. Make a page in /apps/templates/apps/<page.html>
  2. In views.py make a function to return page.html
  3. In urls.py
    1. from apps import views
    2. Supply a url pattern regex and path
    3. Project settings - list app under INSTALLED_APPS
  4. Define a model or models
  5. Apply migrations python manage.py migrate
  6. Make migrations python manage.py makemigrations
  7. Register model in admin.py
    1. from .models import Post
    2. admin.site.register(Post)


Superuser

To begin using the admin interface you need to create a super user:

python manage.py createsuperuser

Security issues options

1. random url for admin interface

2. Very strong password!

Images in Django

Need to install Pillow package

In urls.py need:

from django.conf.urls.static import static
from django.conf import settings

In after urlpatterns [...] include + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Go to settings.py

STATIC_URL = '/static/'
MEDIA_URL = '/pics/'
MEDIA_ROOT = BASE_DIR 

In the .html file to include image use:

<img src="{{  post.image.url }}" />

When using bootstrap ensure images are within a container: <div class="container"> .... </div>

Modify the image tag with: class="img-responsive centre-block" style="max-height:150px;"

Use glyphicon exmaple code to add icons


Troubleshooting

Server running from crashed session

pkill -9 -f runserver