Creating a Model
Now that your environment--"project"--has been built, now it's ready to start working.
Every application you write in Django is made up of Python packages that follow certain conventions under the Python path.
Django comes with a practical tool that automatically generates the basic directory structure of the app, because you can put more effort into coding than creating directories.
Projects vs. Apps (projects and applications)
What's the difference between project and app? An app is a Web application that implements some functionality--for example, a Web blogging system, a public record database, or a simple voting procedure. A project is a collection of specific Web site apps and configurations. A project can contain multiple apps. An app can be in multiple project.
In this tutorial, we will simply create our poll app in the MySite folder. So, this app belongs to this project--mysite, and the Python code in poll app is equivalent to Mysite.polls. At the end of this program, we'll discuss decoupling when you publish your apps.
To create your app, make sure you are in the MySite folder and enter these commands:
Python manage.py Startapp Polls
They will create a polls folder in which the contents are:
polls/
__init__.py
models.py
views.py
The directory structure is the app app.
The first step in writing a database Web application is to define your model layer-basically the layout of your database, but add some extra metadata.
In our simple poll app, we'll create two models: polls and choices. Poll contains question and publication date. Choise has two fields: selected text and voting score. Each choise is associated with a poll.
These concepts can be described in a simple Python class. Edit the file polls/models.py as follows:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()