3. Models
Django uses an ORM (Object-Relational Mapping) to interact with the database. This means that you can use Python to define your models and Django will take care of creating the tables in the database. It's super easy!
It is time to create a model in my_blog/models.py:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
photo = models.ImageField(upload_to='photos/')
description = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Models are classes that represent tables in the database. Each attribute of the class is a field in the table. In this case, we have created an Article model with the fields title, photo, description, and date.
Now create the migration and apply the changes to the database. Open another terminal and run the following commands:
docker compose run --rm django python manage.py makemigrations
docker compose run --rm django python manage.py migrate
The database is now ready. Now let's add some articles.
In our next step we are going to enable the Django admin so that we can add articles from the web interface.
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python
The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.
Buy the bookHelp me keep writing
Every coffee gives me a push toward the next article.
Sure, it's on me!
Comments
There are no comments yet.