Lesson 10 - Admin Views
LEARN
Week 4 - Data
- Lesson 9 - Database
- Lesson 10 - Admin Views
- Lesson 11 - ListView
- Project 4 - Basic Views
- Django for Beginners - Chapter 4
Data Models
- ORM - Object Relational Mapping
- Data Models define the table structure
- Database tables are created by code
Admin views
- Show Data Records
- Allow direct editing of records
- Quick way to build prototypes
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
- Simple database is provided for Development
- Data is stored in db.sqlite3
- Never include a database in Git repo
- MySQL database will replace this
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
- Sensei
- Github repo
- Web app
- Python Anywhere config
- Python Anywhere console
Development Workflow
- Pull code
- Make changes
- Test changes
- Push changes
- Deploy
Data Model
- Create hero/models.py
- Migrate
Admin Views
- Superuser required
- Edit hero/admin.py to add Hero
- Edit config/urls.py to add "admin/"
- Test
Static Files
- Static files must be set up for Admin Views
- Django 'collectstatic' is used to gather files needed
- Admin files will be deployed to Python Anywhere
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
- Show each of the fields in the view
- Create a valid HTML page
- Pass in the hero object
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
- Rerun the django tests
- Add test for "/hero/" page
- Fails because it needs a database
- Switch from SimpleTestCase to TestCase