Skip to content

Instantly share code, notes, and snippets.

@eclecticmiraclecat
Created June 13, 2021 12:52
Show Gist options
  • Save eclecticmiraclecat/6199e99016a3495f2e43c866269f0408 to your computer and use it in GitHub Desktop.
Save eclecticmiraclecat/6199e99016a3495f2e43c866269f0408 to your computer and use it in GitHub Desktop.

Chapter 2. Building a personal CD library.

Starting a django project

$ mkdir chapter2 && cd chapter2
$ django-admin.py startproject djen_project .

Getting started with the App

  • create app
  • add app to project's settings.py
$ python manage.py startapp cd_library
# djen_project/settings.py

INSTALLED_APPS = [
    ...
    'cd_library.apps.CdLibraryConfig',
]

Models

  • description field optional, we pass the null and blank arguments as True
  • genre field should be restricted to tuple values
# cd_library/models.py

from django.db import models

GENRE_CHOICES = (
                 ('R', 'Rock'),
                 ('B', 'Blues'),
                 ('J', 'Jazz'),
                 ('P', 'Pop'),
                )

class CD(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(null=True, blank=True)
    artist = models.CharField(max_length=40)
    date = models.DateField()
    genre = models.CharField(max_length=1, choices=GENRE_CHOICES)

    def __str__(self):
        return "%s by %s, %s" %(self.title, self.artist, self.date.year)

Sync the database

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

Create admin user

$ python manage.py createsuperuser

Add Models to admin page

# cd_library/admin.py

from django.contrib import admin
from .models import CD

admin.site.register(CD)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment