Parcourir la source

django tutorial

Tamas il y a 8 mois
Parent
commit
5ccaa94a25

+ 35 - 5
bin/bonds.ipynb

@@ -109,9 +109,17 @@
     "\n"
    ]
   },
+  {
+   "cell_type": "markdown",
+   "id": "87cc3862-3d54-488c-a125-6db028fa777b",
+   "metadata": {},
+   "source": [
+    "## Amortizing Exercise"
+   ]
+  },
   {
    "cell_type": "raw",
-   "id": "ca78ef5f-b510-4046-9e25-b25774acc50f",
+   "id": "fbe9e927-870b-4e19-88a8-dd7975238610",
    "metadata": {},
    "source": [
     "non-amortizing\n",
@@ -153,16 +161,38 @@
     "2\n",
     "\n",
     "lastBalance(1) \n",
-    "-20\n",
-    "\n",
+    "-20"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 10,
+   "id": "b1adb876-0acb-439f-a32c-5b20d87c0e02",
+   "metadata": {},
+   "outputs": [
+    {
+     "data": {
+      "text/plain": [
+       "'2024-01'"
+      ]
+     },
+     "execution_count": 10,
+     "metadata": {},
+     "output_type": "execute_result"
+    }
+   ],
+   "source": [
+    "import datetime\n",
     "\n",
-    "\n"
+    "now = datetime.datetime.now()\n",
+    "m = f'0{now.month}'[-2:]\n",
+    "f'{now.year}-{m}'"
    ]
   },
   {
    "cell_type": "code",
    "execution_count": null,
-   "id": "b1adb876-0acb-439f-a32c-5b20d87c0e02",
+   "id": "1126d35c-7bf7-4d90-89d2-0d626f4a230f",
    "metadata": {},
    "outputs": [],
    "source": []

+ 68 - 0
bin/kernal_smoothing.py

@@ -0,0 +1,68 @@
+def kernal_smoothing(xaxis_values):
+
+    #USING KERNAL SMOOTHING WEIGHT METHOD TO SMOOTH THE CURVE FOR EACH ANSWER CHOICE 
+
+    global presmoothing_data
+    global kernal_smoothing_weights_df
+    global all_weights_for_j
+    global items_df
+
+    pd.options.mode.chained_assignment = None
+
+    presmoothing_data = pd.DataFrame()
+    kernal_smoothing_weights_df = pd.DataFrame()
+    items_df = pd.DataFrame()
+    presmoothing_data = alldata_forplot[alldata_forplot['item_id'] == x ]
+
+    total_students = len(presmoothing_data.apptnumber.unique())
+    h = 1.1*(total_students**(-.2)) #bandwidth used in smoothing
+
+    items_df[xaxis_values] = [number for number in range(0,total_correct + 1)] 
+    kernal_smoothing_weights_df['Freq'] = presmoothing_data.groupby(xaxis_values).size()
+    kernal_smoothing_weights_df = kernal_smoothing_weights_df.reset_index()
+    kernal_smoothing_weights_df = kernal_smoothing_weights_df.merge(pd.pivot_table(presmoothing_data.groupby([xaxis_values,'response']).size().to_frame('freq'), values='freq', index=[xaxis_values], columns=['response'], fill_value= 0).reset_index(),on=xaxis_values)  
+    kernal_smoothing_weights_df['A_pct'] = kernal_smoothing_weights_df['A'] / kernal_smoothing_weights_df['Freq']
+    kernal_smoothing_weights_df['B_pct'] = kernal_smoothing_weights_df['B'] / kernal_smoothing_weights_df['Freq']
+    kernal_smoothing_weights_df['C_pct'] = kernal_smoothing_weights_df['C'] / kernal_smoothing_weights_df['Freq']
+    kernal_smoothing_weights_df['D_pct'] = kernal_smoothing_weights_df['D'] / kernal_smoothing_weights_df['Freq']
+
+    if MC_options_number == ["5MC"]:
+        kernal_smoothing_weights_df['E_pct'] = kernal_smoothing_weights_df['E'] / kernal_smoothing_weights_df['Freq']            
+
+    kernal_smoothing_weights_df['kernal_smoothing_weight'] = 0
+    kernal_smoothing_weights_df['smoothed_value_A'] = 0
+    kernal_smoothing_weights_df['smoothed_value_B'] = 0
+    kernal_smoothing_weights_df['smoothed_value_C'] = 0
+    kernal_smoothing_weights_df['smoothed_value_D'] = 0
+    kernal_smoothing_weights_df['smoothed_value_E'] = 0
+    kernal_smoothing_weights_df = items_df.merge(kernal_smoothing_weights_df, on=xaxis_values, how='left') 
+    kernal_smoothing_weights_df = kernal_smoothing_weights_df.fillna(0) 
+
+    kernal_smoothing_weights_df_original = kernal_smoothing_weights_df.copy(deep=True)
+
+    for correct in range(0,total_correct + 1):
+        all_weights_for_j = kernal_smoothing_weights_df_original.copy(deep=True)
+        kernal_smoothing_weights_df['bandwidth_var'] = (-1/(2*h))
+        kernal_smoothing_weights_df['var'] = statistics.variance(presmoothing_data[xaxis_values])                                             
+
+        all_weights_for_j['kernal_smoothing_weight'] = np.exp(kernal_smoothing_weights_df['bandwidth_var'] * ((kernal_smoothing_weights_df['num_correct']- correct)**2)  / kernal_smoothing_weights_df['var']) * (kernal_smoothing_weights_df['Freq'])
+
+        kernal_smoothing_weights_df['kernal_smoothing_weight'].iat[correct] = all_weights_for_j['kernal_smoothing_weight'].sum()
+        kernal_smoothing_weights_df['wgt_new'] = all_weights_for_j['kernal_smoothing_weight']
+        kernal_smoothing_weights_df = kernal_smoothing_weights_df.rename(columns={'wgt_new': 'wgt_' + str(correct)})
+
+        all_weights_for_j['smoothed_value_A'] =  ((kernal_smoothing_weights_df["wgt_" + str(correct)]  * kernal_smoothing_weights_df['A_pct']) / kernal_smoothing_weights_df['kernal_smoothing_weight']).replace([np.inf, -np.inf], 0)
+        all_weights_for_j['smoothed_value_B'] =  ((kernal_smoothing_weights_df["wgt_" + str(correct)]  * kernal_smoothing_weights_df['B_pct']) / kernal_smoothing_weights_df['kernal_smoothing_weight']).replace([np.inf, -np.inf], 0)
+        all_weights_for_j['smoothed_value_C'] =  ((kernal_smoothing_weights_df["wgt_" + str(correct)]  * kernal_smoothing_weights_df['C_pct']) / kernal_smoothing_weights_df['kernal_smoothing_weight']).replace([np.inf, -np.inf], 0)
+        all_weights_for_j['smoothed_value_D'] =  ((kernal_smoothing_weights_df["wgt_" + str(correct)]  * kernal_smoothing_weights_df['D_pct']) / kernal_smoothing_weights_df['kernal_smoothing_weight']).replace([np.inf, -np.inf], 0)
+
+        if MC_options_number == ["5MC"]:
+            all_weights_for_j['smoothed_value_E'] =  ((kernal_smoothing_weights_df["wgt_" + str(correct)]  * kernal_smoothing_weights_df['E_pct']) / kernal_smoothing_weights_df['kernal_smoothing_weight']).replace([np.inf, -np.inf], 0)
+
+        kernal_smoothing_weights_df['smoothed_value_A'].iat[correct] = all_weights_for_j['smoothed_value_A'].sum()
+        kernal_smoothing_weights_df['smoothed_value_B'].iat[correct] = all_weights_for_j['smoothed_value_B'].sum()
+        kernal_smoothing_weights_df['smoothed_value_C'].iat[correct] = all_weights_for_j['smoothed_value_C'].sum()
+        kernal_smoothing_weights_df['smoothed_value_D'].iat[correct] = all_weights_for_j['smoothed_value_D'].sum()
+
+        if MC_options_number == ["5MC"]:
+            kernal_smoothing_weights_df['smoothed_value_E'][correct] = all_weights_for_j['smoothed_value_E'].sum()

+ 91 - 0
bin/smoothing.sas

@@ -0,0 +1,91 @@
+%LET SMT=SMOOTHTHIS;
+
+PROC IML;
+    USE TESTVAR;
+    READ ALL VAR{TESTVAR} INTO TESTVAR;
+
+ 
+
+    USE TEMPNEW;
+    READ ALL VAR{&RAW_SCR. COUNT OPTION0 OPTION1 OPTION2 OPTION3 OPTION4 /*OPTION8*/ OPTION9} INTO &SMT.;
+        &SMT.Z=REPEAT(0, NROW(&SMT.), 8);
+        &SMT.=&SMT.||&SMT.Z;
+
+ 
+
+    /*DEFINITION OF THE KERNEL BANDWIDTH*/
+    H=1.1*(SUM(&SMT.[,2])**-.2);
+
+ 
+
+    /*COMPUTATION OF THE KERNEL SMOOTHING WEIGHTS.*/
+    DO I=1 TO NROW(&SMT.);
+        DO J=1 TO NROW(&SMT.);
+            &SMT.[J,10]=EXP((-1/(2*H))*(&SMT.[J,1]-&SMT.[I,1])**2/TESTVAR)*&SMT.[J,2];
+        END;
+
+ 
+
+    /*USE OF THE KERNEL SMOOTHING WEIGHTS IN THE MOVING AVERAGE OF THE CONDITIONAL MEANS.*/
+        DO K=1 TO NROW(&SMT.);
+            DO Q=1 TO 6;
+                &SMT.[I,10+Q]=&SMT.[I,10+Q]+(&SMT.[K,10]*&SMT.[K,Q+2])/SUM(&SMT.[,10]);
+            END;
+        END;
+    END;
+
+ 
+
+    /*EXPORTING THE RESULTS.*/
+    CREATE KSOUT FROM &SMT.;
+    APPEND FROM &SMT.;
+QUIT;
+
+ 
+
+PROC SQL NOPRINT;
+CREATE TABLE KSOUT AS
+SELECT COL1 AS &RAW_SCR., COL2 AS COUNT, 
+   COL3 AS OPTION0, COL11 AS OPTION_KSED_0,
+   COL4 AS OPTION1, COL12 AS OPTION_KSED_1,
+   COL5 AS OPTION2, COL13 AS OPTION_KSED_2,
+   COL6 AS OPTION3, COL14 AS OPTION_KSED_3,
+   COL7 AS OPTION4, COL15 AS OPTION_KSED_4,
+/*   COL8 AS OPTION8, COL16 AS OPTION_KSED_8,*/
+   COL8 AS OPTION9, COL16 AS OPTION_KSED_9
+FROM KSOUT;
+QUIT;
+
+ 
+
+
+PROC TRANSPOSE DATA = KSOUT 
+OUT = KSOUT;
+BY &RAW_SCR.;
+VAR OPTION_KSED_0-OPTION_KSED_4 /*OPTION_KSED_8*/ OPTION_KSED_9;
+RUN;
+
+ 
+
+DATA KSOUT; SET KSOUT;
+ITEM_&I. = INPUT(SUBSTR(_NAME_, 13, 1), 5.);
+RENAME COL1 = KSMTHED_PERCENT;
+DROP _NAME_;
+RUN;
+
+ 
+
+PROC SORT DATA = KSOUT;
+BY ITEM_&I.;
+RUN;
+
+ 
+
+DATA KSOUT;
+  SET KSOUT;
+  BY ITEM_&I.;
+  IF FIRST.ITEM_&I. THEN ID=0;
+  ID+1;
+  IF MOD(ID, 3) = 1 THEN LABEL=ITEM_&I.;
+RUN;
+

BIN
django/tutorial/db.sqlite3


+ 22 - 0
django/tutorial/manage.py

@@ -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()

+ 0 - 0
django/tutorial/mysite/__init__.py


+ 16 - 0
django/tutorial/mysite/asgi.py

@@ -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/5.2/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()

+ 123 - 0
django/tutorial/mysite/settings.py

@@ -0,0 +1,123 @@
+"""
+Django settings for mysite project.
+
+Generated by 'django-admin startproject' using Django 5.2.5.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/5.2/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/5.2/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/5.2/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = "django-insecure-j$@s^kp4c_q9af@r548k0df6kz8@9xe=w)(3sqtot!k#6y11ej"
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+ALLOWED_HOSTS = []
+
+
+# Application definition
+
+INSTALLED_APPS = [
+    "polls.apps.PollsConfig",
+    "django.contrib.admin",
+    "django.contrib.auth",
+    "django.contrib.contenttypes",
+    "django.contrib.sessions",
+    "django.contrib.messages",
+    "django.contrib.staticfiles",
+]
+
+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"
+
+TEMPLATES = [
+    {
+        "BACKEND": "django.template.backends.django.DjangoTemplates",
+        "DIRS": [],
+        "APP_DIRS": True,
+        "OPTIONS": {
+            "context_processors": [
+                "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/5.2/ref/settings/#databases
+
+DATABASES = {
+    "default": {
+        "ENGINE": "django.db.backends.sqlite3",
+        "NAME": BASE_DIR / "db.sqlite3",
+    }
+}
+
+
+# Password validation
+# https://docs.djangoproject.com/en/5.2/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/5.2/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/5.2/howto/static-files/
+
+STATIC_URL = "static/"
+
+# Default primary key field type
+# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
+
+DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

+ 25 - 0
django/tutorial/mysite/urls.py

@@ -0,0 +1,25 @@
+"""
+URL configuration for mysite project.
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+    https://docs.djangoproject.com/en/5.2/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 include, path
+
+urlpatterns = [
+    path("polls/", include("polls.urls")),
+    path("admin/", admin.site.urls),
+]

+ 16 - 0
django/tutorial/mysite/wsgi.py

@@ -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/5.2/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()

+ 0 - 0
django/tutorial/polls/__init__.py


+ 7 - 0
django/tutorial/polls/admin.py

@@ -0,0 +1,7 @@
+from django.contrib import admin
+
+from .models import Question, Choice
+
+
+admin.site.register(Question)
+admin.site.register(Choice)

+ 6 - 0
django/tutorial/polls/apps.py

@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class PollsConfig(AppConfig):
+    default_auto_field = "django.db.models.BigAutoField"
+    name = "polls"

+ 24 - 0
django/tutorial/polls/models.py

@@ -0,0 +1,24 @@
+import datetime
+
+from django.db import models
+from django.utils import timezone
+
+class Question(models.Model):
+    question_text = models.CharField(max_length=200)
+    pub_date = models.DateTimeField("date published")
+
+    def was_published_recently(self):
+        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
+
+
+    def __str__(self):
+        return self.question_text
+
+
+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

+ 24 - 0
django/tutorial/polls/templates/polls/detail.html

@@ -0,0 +1,24 @@
+<!doctype html>
+<html lang="en-US">
+  <head>
+    <meta charset="utf-8" />
+    <title>{{ question.question_text }}</title>
+  </head>
+  <body>
+    <a href="/polls">Back</a>
+
+<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>
+  </body>
+</html>
+

+ 21 - 0
django/tutorial/polls/templates/polls/index.html

@@ -0,0 +1,21 @@
+<!doctype html>
+<html lang="en-US">
+  <head>
+    <meta charset="utf-8" />
+    <title>Questions</title>
+  </head>
+  <body>
+<h1> Questions </h1>
+
+    {% if latest_question_list %}
+    <ul>
+    {% for question in latest_question_list %}
+	<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
+    {% endfor %}
+    </ul>
+	{% else %}
+    	<p>No polls are available.</p>
+    {% endif %}
+  </body>
+</html>
+

+ 53 - 0
django/tutorial/polls/templates/polls/math.html

@@ -0,0 +1,53 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>Math</title>
+  <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script>
+</head>
+<body>
+When \(a \ne 0\), there are two solutions to \(ax^2 + bx + c = 0\) and they are
+$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
+
+<?xml version="1.0" encoding="UTF-8"?>
+<math xmlns="http://www.w3.org/1998/Math/MathML" alttext="\mathbf{F}_{2}=k\frac{q_{1}q_{2}\hat{\mathbf{r}}_{21}}{r_{21}^{2}}" display="block">
+  <mrow>
+    <msub>
+      <mi>𝐅</mi>
+      <mn>2</mn>
+    </msub>
+    <mo>=</mo>
+    <mrow>
+      <mi>k</mi>
+      <mo>⁢</mo>
+      <mfrac>
+        <mrow>
+          <msub>
+            <mi>q</mi>
+            <mn>1</mn>
+          </msub>
+          <mo>⁢</mo>
+          <msub>
+            <mi>q</mi>
+            <mn>2</mn>
+          </msub>
+          <mo>⁢</mo>
+          <msub>
+            <mover accent="true">
+              <mi>𝐫</mi>
+              <mo stretchy="false">^</mo>
+            </mover>
+            <mn>21</mn>
+          </msub>
+        </mrow>
+        <msubsup>
+          <mi>r</mi>
+          <mn>21</mn>
+          <mn>2</mn>
+        </msubsup>
+      </mfrac>
+    </mrow>
+  </mrow>
+</math>
+</body>
+</html>

+ 18 - 0
django/tutorial/polls/templates/polls/results.html

@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>Results</title>
+</head>
+<body>
+<h1>{{ question.question_text }}</h1>
+
+<ul>
+{% for choice in question.choice_set.all %}
+    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
+{% endfor %}
+</ul>
+
+<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
+</body>
+</html>

+ 3 - 0
django/tutorial/polls/tests.py

@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.

+ 12 - 0
django/tutorial/polls/urls.py

@@ -0,0 +1,12 @@
+from django.urls import path
+
+from . import views
+
+app_name = "polls"
+urlpatterns = [
+    path("math/", views.math, name="math"),
+    path("", views.IndexView.as_view(), name="index"),
+    path("<int:pk>/", views.DetailView.as_view(), name="detail"),
+    path("<int:pk>/results/", views.ResultsView.as_view(), name="results"),
+    path("<int:question_id>/vote/", views.vote, name="vote"),
+]

+ 56 - 0
django/tutorial/polls/views.py

@@ -0,0 +1,56 @@
+
+from django.db.models import F
+from django.http import HttpResponseRedirect
+from django.shortcuts import get_object_or_404, render
+from django.urls import reverse
+from django.views import generic
+
+from .models import Choice, Question
+
+
+class IndexView(generic.ListView):
+    template_name = "polls/index.html"
+    context_object_name = "latest_question_list"
+
+    def get_queryset(self):
+        """Return the last five published questions."""
+        return Question.objects.order_by("-pub_date")[:5]
+
+
+class DetailView(generic.DetailView):
+    model = Question
+    template_name = "polls/detail.html"
+
+
+class ResultsView(generic.DetailView):
+    model = Question
+    template_name = "polls/results.html"
+
+
+def vote(request, question_id):
+    question = get_object_or_404(Question, pk=question_id)
+    try:
+        selected_choice = question.choice_set.get(pk=request.POST["choice"])
+    except (KeyError, Choice.DoesNotExist):
+        # Redisplay the question voting form.
+        return render(
+            request,
+            "polls/detail.html",
+            {
+                "question": question,
+                "error_message": "You didn't select a choice.",
+            },
+        )
+    else:
+        selected_choice.votes = F("votes") + 1
+        selected_choice.save()
+        # Always return an HttpResponseRedirect after successfully dealing
+        # with POST data. This prevents data from being posted twice if a
+        # user hits the Back button.
+        return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))
+
+
+def math(request):
+    latest_question_list = Question.objects.order_by("-pub_date")[:5]
+    context = {"latest_question_list": latest_question_list}
+    return render(request, "polls/math.html", context)