Tuesday, October 29, 2019

PollOpinion site in Django-2 ( Creating the polls app)

A Django project is organized as a group of individual apps that work together to make the project work as a whole. For now, we’ll create a polls app and later we'll create other apps as and when required. Please make sure you still have running runserver in the terminal window as we did in the previous post.

Open a new terminal window and navigate to the directory that contains manage.py. Activate the virtual environment, and then run the startapp command:

C:\Users\Python>cd C:\Projects\PollSite

C:\Projects\PollSite>pollsite_env\Scripts\activate


(pollsite_env) C:\Projects\PollSite>python manage.py startapp polls

(pollsite_env) C:\Projects\PollSite>


The command startapp appname tells Django to create the infrastructure needed to build an app. If you look in the project directory now, you’ll see a new folder called polls. Open this folder to see the file structure Django created for our app:





The most important files are models.py, admin.py, and views.py. We’ll use models.py to define the data we want to manage in our app.

Defining Question model

We will create a number of questions in our PollSite. Each entry we make will be tied to
a question and these entries will be displayed as text. We’ll also need to store the timestamp of each entry so we can show users when we made each entry.

Open the file models.py, and look at its existing content:

from django.db import models
# Create your models here.


A module called models is being imported for us, and we can create models of our own. A model tells Django how to work with the data that will be stored in the app. Code-wise, a model is just a class; it has attributes and methods, just like every class. Here’s the model for the topics users will store:

from django.db import models

# Create your models here.


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


    def __str__(self):
        return self.question_text


We’ve created a class called Question, which inherits from Model—a parent class included in Django that defines the basic functionality of a model. Only two attributes are in the Question class: question_text and pub_date.

The question_textis a CharField—a piece of data that’s made up of characters, or text. We use CharField when we want to store a small amount of text, such as a name, a title, or a city. When we define a CharField attribute, we have to tell Django how much space it should reserve in the database. Here we give it a max_length of 200 characters, which should be enough to hold most topic names.

The pub_date attribute is a DateTimeField—a piece of data that will record a date and time. We pass the argument date published which tells Django to automatically set this attribute to the date and time
whenever the user creates a new question .

We need to tell Django which attribute to use by default when it displays information about a question. Django calls a __str__() method to display a simple representation of a model. Here we’ve written a __str__() method that returns the string stored in the text attribute.

Activating Question model





To use our models, we have to tell Django to include our app in the overall project. Open settings.py (in the C:\Projects\PollSite\Poll_Opinion directory), and you’ll see a section that tells Django which apps are installed in the project:


INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
--snip--

This is just a tuple, telling Django which apps work together to make up the project. Add our app to this tuple by modifying INSTALLED_APPS so it looks like this:

--snip--
INSTALLED_APPS = (
--snip--
'django.contrib.staticfiles',
# My apps
'polls.apps.PollsConfig',
)
--snip--

Next, we need to tell Django to modify the database so it can store information related to the model Question. From the terminal, run the following command:

(pollsite_env) C:\Projects\PollSite>python manage.py makemigrations polls

Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model Question

(pollsite_env) C:\Projects\PollSite>



The command makemigrations tells Django to figure out how to modify the database so it can store the data associated with any new models we’ve defined. The output here shows that Django has created a migration file called 0001_initial.py. This migration will create a table for the model Question in the database. Now we’ll apply this migration and have Django modify the database
for us:


(pollsite_env) C:\Projects\PollSite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK

Most of the output from this command is identical to the output from the first time we issued the migrate command. The line we need to check appears at last, where Django confirms that everything worked OK when it applied the migration for polls.

Whenever we want to modify the data that PollOpinion  manages,we’ll follow these three steps: modify models.py, call makemigrations on polls, and tell Django to migrate the project.
Share:

0 comments:

Post a Comment