Django Models.py Setup

PROJECTNAME/APPNAME/models.py

  • Create a new Class for each Table in the Database
  • Create __str__() function to display information in HTML Dashbaord
from django.db import models

class Note(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=255)
    note = models.TextField()

    def __str__(self):
        return f"{self.timestamp} --- {self.title} --- {self.note}"

PROJECTNAME/APPNAME/admin.py

  • Edit admin.py to register the table in the HTML Dashboard
from django.contrib import admin

from .models import Note

admin.site.register(Note)Code language: JavaScript (javascript)

Update Database with model.py Changes

  • Run makemigrations and migrate to update the database with the new configurations
python3 manage.py makemigrations APPNAME
python3 manage.py migrateCode language: CSS (css)

PROJECTNAME/APPNAME/views.py

  • Import the Table into the views.py file (Note)
from django.template import loader
from .models import Note

def report(request):
  template = loader.get_template("report.html")
  notes = Note.objects.all().values()
  context = {
    'notes': notes,
  }
  return HttpResponse(template.render(context, request))Code language: JavaScript (javascript)