MNNIT CC 2021-22 Classes

Web Development Class - VI

Web Development Class - VI recording: Here

May 12, 2021

Polling App in Django

Prerequisite

What is polling app?

Creating a new app

python manage.py startapp polls
# In project1/settings.py file
INSTALLED_APPS = [
	'polls.apps.PollsConfig',

	# Below are the pre-installed apps which were already present
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Writing our first view

# In project1/polls/views.py file
from django.shortcuts import render, HttpResponse

def hello_world(request):
	print("This is my first view! Hello World!")
	return HttpResponse("Hello World!")

Mapping view with URL

# In project1/urls.py file
urlpatterns = [
	path("", include("polls.urls")),
	path("admin/", admin.site.urls),
]
# In project1/polls/urls.py file
from django.urls import path
from polls import views

urlpatterns = [
	path("", views.hello_world),
]

Testing our first view

python manage.py runserver

Desiging database for polls app

















Recap: Django Models

Creating models for our app

# In project1/polls/models.py
class Question(models.Model):  # Model class from models module is inherited in class Question.
    
    question_text = models.CharField(max_length=1000, verbose_name="Text")

    publication_date = models.DateField(verbose_name="Publication Date")

    def __str__(self):  #  A method is declared so that in admin panel Text of Question is displayed.
        return self.question_text

# In project1/polls/models.py
class Choice(models.Model):

    choice_text = models.CharField(max_length=200, verbose_name="Choice Text")

    number_of_votes = models.IntegerField(verbose_name="Number of Votes")

    question = models.ForeignKey(Question, on_delete=models.CASCADE)

    def __str__(self):
        return self.choice_text

Django Admin Panel

python manage.py runserver

python manage.py createsuperuser
# In project1/polls/admin.py file
from .models import Question, Choice

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

Users Table

Recap: Steps involed in Making/Editing a Table/Model in Django

Content Contributors

Materials