Thursday, October 31, 2019

PollOpinion site in Django-4 ( Making pages for the PollSite)

In Django making web pages consists of three stages: defining URLs, writing views, and writing templates. First, you must define patterns for URLs. A URL pattern describes the way the URL is laid out and tells Django what to look for when matching a browser request with a site URL so it knows which page to return.

Each URL then maps to a particular view—the view function retrieves and processes the data needed for that page. The view function often calls a template, which builds a page that a browser can read. It's better to make a home page for our Pollsite and see how the three stages I just mentioned actually works.

We request pages by entering URLs into a browser and clicking links, so we’ll need to decide what URLs are needed in our project. The home page URL is first: it’s the base URL people use to access the project. At the moment, the base URL, http://localhost:8000/, returns the default Django site that lets us know the project was set up correctly. We’ll change this by mapping the base URL to Pollsite’s home page.

From C:\Projects\PollSite\Poll_Opinion open the urls.py file whose content is shown below:

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

In this urls.py file, which represents the project as a whole, the urlpatterns variable includes sets of URLs from the apps in the project. The code in the path()method includes the module admin.site.urls, which defines all the URLs that can be requested from the admin site. Here we'll add the code to our home page as shown below:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
  
    path('admin/', admin.site.urls),
    path('', include('polls.urls')),
]
Now we need to make a second urls.py file in the C:\Projects\PollSite\polls folder and add the following code to it:

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    # Home page
    path('', views.IndexView.as_view(), name='index'),
   
    ]

We import path from the django.urls module needed to map the urls to views. We also import the views module ; the dot tells Python to import views from the same directory as the current urls.py module. The variable urlpatterns in this module is a list of individual pages that can be requested from the Polls app.

The actual URL pattern is a call to the path() function, which takes three arguments. The first is a regular expression. Django will look for a regular expression in urlpatterns that matches the requested URL string. Therefore, a regular expression will define the pattern that Django can look for.

In its entirety, this expression tells Python to look for a URL with nothing between the beginning and end of the URL. Python ignores the base URL for the project (http://localhost:8000/), so an empty regular expression matches the base URL. Any other URL will not match this expression, and Django will return an error page if the URL requested doesn’t match any existing URL patterns.

The second argument in path() specifies which view function to call. When a requested URL matches the regular expression, Django will call views.index (we’ll write this view function soon).

The third argument provides the name index for this URL pattern so we can refer to it in other sections of the code. Whenever we want to provide a link to the home page, we’ll use this name instead of writing out a URL.

Out of the three stages we mentioned in the beginning of this post we have completed the first stage, now we'll move on to the second stage which is writing a view function. A view function takes in information from a request, prepares the data needed to generate a page, and then sends the data back to the browser, often by using a template that defines what the page will look like.

The file views.py in C:\Projects\PollSite\polls was generated automatically when we ran the command python manage.py startapp. Here’s what’s in views.py right now:

from django.shortcuts import render

# Create your views here.

Currently, this file just imports the render() function, which renders the response based on the data provided by views. The following code is how the view for the home page should be written:

from django.shortcuts import render

# Create your views here.

def index(request):
    """The home page for Learning Log"""
    return render(request, 'polls/index.html')


When a URL request matches the pattern we just defined, Django will look for a function called index() in the views.py file. Django then passes the request object to this view function. In this case, we don’t need to process any data for the page, so the only code in the function is a call to render().
The render() function here uses two arguments—the original request object and a template it can use to build the page. Let’s write this template now which is the third and final stage to create a web page.

A template sets up the structure for a web page and defines what the page should look like, and Django fills in the relevant data each time the page is requested. A template allows us to access any data provided by the view. As for now our view for the home page provided no data, this template is fairly simple.

We need to create a directory structure first in the C:\Projects\PollSite\polls folder. Make a new folder called templates. Inside the templates folder, make another folder called polls. This sets up a structure that Django can interpret unambiguously, even in the context of a large project containing many individual apps. Inside the inner polls folder (C:\Projects\PollSite\polls\templates\polls), make a new file called index.html. Add the following code into that file:

<p>Poll Questions</p>

<p>Click on the question to take part in the Poll</p>

Now that our template is ready we have fulfilled the criteria for the web page creation. Now when we request the project’s base URL, http://localhost:8000/, we’ll see the page we just built instead of the default Django page. Django will take the requested URL, and that URL will match the pattern ' '; then Django will call the function views.index(), and this will render the page using the template contained in index.html. The resulting page should be as shown below:



We have just created our first webpage, the home page for our poll application. In our poll application, we’ll have the following four views:

Question “index” page – displays the latest few questions.
Question “detail” page – displays a question text, with no results but with a form to vote.
Question “results” page – displays results for a particular question.
Vote action – handles voting for a particular choice in a particular question.

In the coming posts we shall create each of these pages.







Share:

PollOpinion site in Django-3 ( The Django Admin Site)

When we define models for an app, Django makes it easy for us to work with our models through the admin site. A site’s administrators use the admin site, not a site’s general users. Now we’ll set up the admin site and use it to add some questions through the Question model.

Creating a superuser

Django allows you to create a user who has all privileges available on the site, called a superuser. A privilege controls the actions a user can take. The most restrictive privilege settings allow a user to only read public information on the site. Registered users typically have the privilege of reading their own private data and some selected information available only to members. To effectively administer a web application, the site owner usually needs access to all information stored on the site. To create a superuser in Django, enter the following command and respond to the prompts:

(pollsite_env) C:\Projects\PollSite>python manage.py createsuperuser
Username (leave blank to use 'python'): pollsite_admin
Email address:
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

(pollsite_env) C:\Projects\PollSite>


When you issue the command createsuperuser, Django prompts you to enter a username for the superuser. Here we’re using pollsite_admin, but you can enter any username you want. You can enter an email address if you want or just leave this field blank. You’ll need to enter your password twice. I have used a simple password hence I choose to Bypass password validation.

Registering a Model with the Admin Site

Django includes some models in the admin site automatically, such as User and Group, but the models we create need to be registered manually.  From C:\Projects\PollSite\polls directory open admin.py file to register the Question Model:

from django.contrib import admin
from .models import Question

# Register your models here.

admin.site.register(Question)


This code imports the model we want to register Question Model and then uses admin.site.register() to tell Django to manage our model through the admin site.

Go to http://localhost:8000/admin/, enter the username and password for the superuser we just created, and you should see a screen like the one shown below:



In case the model doesn't show then restart the server running in the other terminal by executing python manage.py runserver command.

We can add questions by clicking the Add button button at this stage the complete functionality of the project has not been implemented. So instead of adding questions we'll move on to create our next model, Choice which will give us options to select an answer for the Question asked in Poll. The code for the Choice model is shown below:

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
   
    def __str__(self):
        return self.choice_text

Add this code to the models.py file. The Choice model has two fields: the text of the choice and a vote tally. Each Choice is associated with a Question and this relationship is defined, using ForeignKey that tells Django each Choice is related to a single Question. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.

As we’ve added a new model, we need to migrate the database again. Run the command python manage.py makemigrations polls, and then run the command python manage.py migrate. Migrate the database and check the output:

(pollsite_env) C:\Projects\PollSite>python manage.py makemigrations polls
Migrations for 'polls':
  polls\migrations\0002_choice.py
    - Create model Choice

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

(pollsite_env) C:\Projects\PollSite>

A new migration called 0002_choice.py is generated, which tells Django how to modify the database to store information related to the model Choice. When we issue the migrate command, we see that Django applied this migration, and everything was okay. As we did before for the Question model, we'll register the Choice model with the admin.py. Modify the admin.py file as shown below:

from django.contrib import admin
from .models import Question,Choice

# Register your models here.

admin.site.register(Question)
admin.site.register(Choice)

Go back to http://localhost/admin/, and you should see Choices listed under Questions. It’s important to add __str__() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s  automatically-generated admin.

Note these are normal Python methods. Let’s add a custom method to the Question model as shown below:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
   
    def __str__(self):
        return self.question_text
       
    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now


We'll use this function later as of now this was just to demonstrate how to create custom method in our models. We also have to import the respective modules like the datetime and from django.utils import timezone, to reference Python’s standard datetime module and Django’s time-zone-related utilities in django.utils.timezone, respectively.









Share:

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: