UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 10 - Admin Views

LEARN

Week 4 - Data

Data Models

Admin views

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)

hero/admin.py

from django.contrib import admin
from .models import Hero

admin.site.register(Hero)

Migration

Examine code for changes to Data Models

$ python manage.py makemigrations

Apply changes to Data Tables

$ python manage.py migrate

Development Database

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

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

BUILD - Development Workflow

Short-cuts

Development Workflow

Data Model

Admin Views

Static Files

Collecting the Static Files

config/settings

# Place to collect static files
STATIC_ROOT = BASE_DIR / "static_assets"

Move the files into static directory

$ mv static_assets/admin static/admin

$ rm -rf static_assets

$ git commit -am 'Add Admin static files'

Test and fix

$ python manage.py runserver
$ browse to 127.0.0.1:8000/admin/
$ git add . && git commit -m "Hero List View"

Fix display of Hero

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

Tests