UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 9 - Database

LEARN

Week 1 - Setup Development Tools

Week 2 - Build a Django Project

Week 3 - Web App Hosting

Week 4 - Data

Data Models

Hero Data Model

hero/models.py

from django.db import models

class Hero (models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    image = models.CharField(max_length=200)

Migration

Examine code for changes to Data Models

$ python manage.py makemigrations

Apply changes to Data Tables

$ python manage.py migrate

BUILD - Development Workflow

Short-cuts

Development Workflow

Pull code

Before you start working

$ git pull

Make changes

Test changes

Commit changes

Commit and push each hour

$ git add . 
$ git commit -m 'Week 4 - admin views'
$ git push

BUILD - New Project

Create Project

$ cd BACS350; mkdir week4/Superhero && cd week4/Superhero
$ django-admin startproject config .
$ python manage.py startapp hero
$ python manage.py runserver

Settings

config/settings.py

# Enable the templates for the 'templates' directory

TEMPLATES = [
    {
        ...
        'DIRS': ['templates'],
        ...
    },
]


# Enable the static media server (Images, CSS, Javascript)

STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]


# Enable Python Anywhere

ALLOWED_HOSTS = ['markseaman.pythonanywhere.com', '127.0.0.1']


# Enable data for Hero app

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hero',
]

Templates

templates/index.html

<h1>Superhero Gallery</h1>

<a href="/admin/">Django Admin Views</a>

Views

hero/views.py

from django.views.generic import TemplateView

class IndexView(TemplateView):
    template_name = 'index.html'

URLs

config/urls.py

from django.urls import path
from hero.views import IndexView
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', IndexView.as_view()),
]

Test and fix

Test the app

$ python manage.py runserver
$ browse to 127.0.0.1:8000

Create a super user

$ python manage.py createsuperuser

Django Tests

hero/tests.py

from django.test import SimpleTestCase

class SimpleTests(SimpleTestCase):
    def test_home_page_status_code(self):
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)

Run all tests

$ python manage.py test

BUILD - Application Deployment

Python Anywhere Setup

Create Virtual Environment

Delete Your Web App

Switching Web Apps