UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 12 - Data CRUD Operations

LEARN

Week 5 - Data

Visit the Django website

Applications = Data + Views

ORM - Object Relational Mapper

Database

Two Views of Data

Superhero Data Model

Data Migration

CRUD Operations

Operations on Every Model

Change in Demos

Book Builder App

Django Admin View

BUILD

Short-cuts

Development Workflow

Start Book Builder project

$ cd week5/BookBuilder
$ django-admin startproject config .
$ python manage.py startapp book

Settings

config/settings.py

# Enable the templates for the 'templates' directory

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


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

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


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


# Enable Python Anywhere

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


# 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',
    'book',
]

Add Data Model

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)

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

Enable Admin Views on Book

book/admin.py

from django.contrib import admin
from .models import Book

admin.site.register(Book)

Test Admin Book

$ python manage.py createsuperuser
$ python manage.py runserver
$ browse to 127.0.0.1:8000/admin/
$ git add . && git commit -m "Book Data Model"

Python CRUD

Terminal Window

$ python manage.py shell

Use the Book Model

from book.models import Book

List Books

Book.objects.all()

Book.objects.filter(author='Mark Seaman')

Get specific book

b = Book.objects.get(title="A Seaman's Journey")
b.author
b.name
b.pk

Create book record

Book.objects.create(title="A Seaman's Journey", author="Mark Seaman")

Update book record

b = Book.objects.get(title="A Seaman's Journey")
b.title = "A Seaman's Life"
b.save()

Delete a record

Book.objects.get(title="A Seaman's Journey").delete()

Practice

CRUD Code

Data Model

hero/models.py

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

CREATE

Superhero.objects.create(name='Black Widow', description='Natalia Romanova', image='None')

READ

w = Superhero.objects.get(name='Black Widow')
print(w.description)

for s in Superhero.objects.all():
    print(w.description, w.name)

UPDATE

w = Superhero.objects.get(name='Black Widow')
w.description='Natasha Romanoff'
w.save()

DELETE

Superhero.objects.get(name='Black Widow').delete()