Skip to content

Commit

Permalink
Poll Application made using Django
Browse files Browse the repository at this point in the history
  • Loading branch information
ShashwatGupta2001 committed Mar 17, 2022
0 parents commit a7e0fdf
Show file tree
Hide file tree
Showing 37 changed files with 627 additions and 0 deletions.
1 change: 1 addition & 0 deletions Helper.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Glossary: https://docs.djangoproject.com/en/4.0/glossary/#term-project
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Tutorials:

Documentation:
https://docs.djangoproject.com/en/dev/

Where to Go:
https://docs.djangoproject.com/en/4.0/intro/whatsnext/

Index:
https://docs.djangoproject.com/en/4.0/contents/
Binary file added db.sqlite3
Binary file not shown.
22 changes: 22 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Empty file added mysite/__init__.py
Empty file.
Binary file added mysite/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added mysite/__pycache__/settings.cpython-310.pyc
Binary file not shown.
Binary file added mysite/__pycache__/urls.cpython-310.pyc
Binary file not shown.
Binary file added mysite/__pycache__/wsgi.cpython-310.pyc
Binary file not shown.
16 changes: 16 additions & 0 deletions mysite/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for mysite project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

application = get_asgi_application()
126 changes: 126 additions & 0 deletions mysite/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 4.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-5cm$3^p=5_zpj2$v#dpt$%j77lm)896v#3()sy&xd#6$%yzi!6'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [ # apps in django are pluggable

'django.contrib.admin', # admin site
'django.contrib.auth', # authentication
'django.contrib.contenttypes', # framework for content types
'django.contrib.sessions', # session framework
'django.contrib.messages', # messages framework
'django.contrib.staticfiles', # static files management framework

'polls.apps.PollsConfig', # polls app
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls' # where to look for urls

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
9 changes: 9 additions & 0 deletions mysite/templates/admin/base_site.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{% extends "admin/base.html" %}

{% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Django Site Administrator') }}{% endblock %}

{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administrator</a></h1>
{% endblock %}

{% block nav-global %}{% endblock %}
24 changes: 24 additions & 0 deletions mysite/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include # unclude() is used to include another URLconf

urlpatterns = [
path('polls/', include('polls.urls')), # pointing the root url conf at the polls.urls
path('admin/', admin.site.urls),
]

# path( route, view, kwargs, name )
16 changes: 16 additions & 0 deletions mysite/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

application = get_wsgi_application()
Empty file added polls/__init__.py
Empty file.
Binary file added polls/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added polls/__pycache__/admin.cpython-310.pyc
Binary file not shown.
Binary file added polls/__pycache__/apps.cpython-310.pyc
Binary file not shown.
Binary file added polls/__pycache__/models.cpython-310.pyc
Binary file not shown.
Binary file added polls/__pycache__/tests.cpython-310.pyc
Binary file not shown.
Binary file added polls/__pycache__/urls.cpython-310.pyc
Binary file not shown.
Binary file added polls/__pycache__/views.cpython-310.pyc
Binary file not shown.
54 changes: 54 additions & 0 deletions polls/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from django.contrib import admin

# Register your models here.

# Adding Questions:

from .models import Question

# M1
# # admin.site.register(Question)

# M2
# class QuestionAdmin(admin.ModelAdmin):
# fields = ['pub_date', 'question_text']

# admin.site.register(Question, QuestionAdmin)

# M3
# Splitting the two field choices
# class QuestionAdmin(admin.ModelAdmin):
# fieldsets = [
# (None, {'fields': ['question_text']}),
# ('Date information', {'fields': ['pub_date']}),
# ]

# admin.site.register(Question, QuestionAdmin)

# Adding Choices:

# M1
from .models import Choice
# admin.site.register(Choice)

# M2
class ChoiceInline(admin.TabularInline): # TabularInline uses less space on screen
#class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3


class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]

list_display = ('question_text', 'pub_date', 'was_published_recently')

list_filter = ['pub_date']

search_fields = ['question_text']

admin.site.register(Question, QuestionAdmin)
6 changes: 6 additions & 0 deletions polls/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class PollsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'polls'
32 changes: 32 additions & 0 deletions polls/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Generated by Django 4.0.3 on 2022-03-03 10:52

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
],
),
migrations.CreateModel(
name='Choice',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('choice_text', models.CharField(max_length=200)),
('votes', models.IntegerField(default=0)),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.question')),
],
),
]
Empty file added polls/migrations/__init__.py
Empty file.
Binary file not shown.
Binary file not shown.
32 changes: 32 additions & 0 deletions polls/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from django.contrib import admin
from django.db import models
from django.utils import timezone
import datetime

# Create your models here.


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

def __str__(self): # called when print() or str() is invoked on the object;
return self.question_text # without _str_() it would return the object's memory address by _repr_()


@admin.display(
boolean=True,
ordering='pub_date',
description='Published recently?',
)
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now

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): # self is the analogue to this in C++
return self.choice_text
Binary file added polls/static/images/background.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions polls/static/polls/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
li a {
color: green;
}

body {
background: white url("images/background.gif") no-repeat;
}
12 changes: 12 additions & 0 deletions polls/templates/polls/detail.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
<legend><h1>{{ question.question_text }}</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
</fieldset>
<input type="submit" value="Vote">
</form>
Loading

0 comments on commit a7e0fdf

Please sign in to comment.