12. Creating Blog app & setting up models
"A Django application is just a Python package that is specifically intended for use in a Django project. An application may use common Django conventions, such as having models, tests, urls, and views submodules.
Later on we use the term packaging to describe the process of making a Python package easy for others to install."
- from Package? App?.
We're going to make a small blog app to see how we can use database. It has title, body, and publish data etc.
~/Django/DjangoVirtualenv$ source bin/activate (DjangoVirtualenv)k@HP-Notebook:~/Django/DjangoVirtualenv$ pwd /home/k/Django/DjangoVirtualenv (DjangoVirtualenv)k@HP-Notebook:~/Django/DjangoVirtualenv$ tree -L 2
To create an app, we use managy.py, so we need to go inside project directory:
$ cd DjangoTestProject $ pwd /home/k/Django/DjangoVirtualenv/DjangoTestProject $ ls DjangoTestProject manage.py $ python manage.py startapp blog
Now, we have blog in the file structure:
Note that our blog app contains a special file __init__.py, even if this file is empty (size == 0). We need that file for our app to be imported as a module later.
We have other files as well: models.py, tests.py, and views.py. But in this chapter, we'll focus on the models.py which is related to database.
We're going to work on models.py:
A model is all about our data. It contains the essential fields and behaviors of the data we're storing. In general, each model maps to a single database table.
- Each model is a Python class that subclasses django.db.models.Model.
- Each attribute of the model represents a database field.
- With all of this, Django gives us an automatically-generated database-access API.
$ cd blog $ gedit models.py
Here is the modified models.py:
from django.db import models # Create your models here. class Blog(models.Model): title = models.CharField(max_length=250) body = models.TextField() publish_date = models.DateTimeField('published date') gPlus = models.IntegerField()
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization