adddddd
This commit is contained in:
commit
3dcb765e5b
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
venv/
|
||||||
|
db.sqlite3
|
||||||
|
*.pyc
|
22
manage.py
Executable file
22
manage.py
Executable file
@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
|
||||||
|
try:
|
||||||
|
from django.core.management import execute_from_command_line
|
||||||
|
except ImportError:
|
||||||
|
# The above import may fail for some other reason. Ensure that the
|
||||||
|
# issue is really that Django is missing to avoid masking other
|
||||||
|
# exceptions on Python 2.
|
||||||
|
try:
|
||||||
|
import django
|
||||||
|
except ImportError:
|
||||||
|
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?"
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
execute_from_command_line(sys.argv)
|
0
mysite/__init__.py
Normal file
0
mysite/__init__.py
Normal file
121
mysite/settings.py
Normal file
121
mysite/settings.py
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
"""
|
||||||
|
Django settings for Mark Test Django project.
|
||||||
|
|
||||||
|
Generated by 'django-admin startproject' using Django 1.11.
|
||||||
|
|
||||||
|
For more information on this file, see
|
||||||
|
https://docs.djangoproject.com/en/1.11/topics/settings/
|
||||||
|
|
||||||
|
For the full list of settings and their values, see
|
||||||
|
https://docs.djangoproject.com/en/1.11/ref/settings/
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||||
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
|
|
||||||
|
# Quick-start development settings - unsuitable for production
|
||||||
|
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
|
||||||
|
|
||||||
|
# SECURITY WARNING: keep the secret key used in production secret!
|
||||||
|
SECRET_KEY = 'nmh%1k0^iwu6=5)l78149i3zd8yvghurgw#57x^xm%#m65dj(l'
|
||||||
|
|
||||||
|
# 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': [os.path.join(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/1.11/ref/settings/#databases
|
||||||
|
|
||||||
|
DATABASES = {
|
||||||
|
'default': {
|
||||||
|
'ENGINE': 'django.db.backends.sqlite3',
|
||||||
|
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Password validation
|
||||||
|
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/
|
||||||
|
|
||||||
|
LANGUAGE_CODE = 'pl-PL'
|
||||||
|
|
||||||
|
TIME_ZONE = 'UTC'
|
||||||
|
|
||||||
|
USE_I18N = True
|
||||||
|
|
||||||
|
USE_L10N = True
|
||||||
|
|
||||||
|
USE_TZ = True
|
||||||
|
|
||||||
|
|
||||||
|
# Static files (CSS, JavaScript, Images)
|
||||||
|
# https://docs.djangoproject.com/en/1.11/howto/static-files/
|
||||||
|
|
||||||
|
STATIC_URL = '/static/'
|
22
mysite/urls.py
Normal file
22
mysite/urls.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
"""mysite URL Configuration
|
||||||
|
|
||||||
|
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||||
|
https://docs.djangoproject.com/en/1.11/topics/http/urls/
|
||||||
|
Examples:
|
||||||
|
Function views
|
||||||
|
1. Add an import: from my_app import views
|
||||||
|
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
|
||||||
|
Class-based views
|
||||||
|
1. Add an import: from other_app.views import Home
|
||||||
|
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
|
||||||
|
Including another URLconf
|
||||||
|
1. Import the include() function: from django.conf.urls import url, include
|
||||||
|
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
|
||||||
|
"""
|
||||||
|
from django.conf.urls import include, url
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
url(r'^polls/', include('polls.urls')),
|
||||||
|
url(r'^admin/', admin.site.urls),
|
||||||
|
]
|
16
mysite/wsgi.py
Normal file
16
mysite/wsgi.py
Normal file
@ -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/1.11/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
polls/__init__.py
Normal file
0
polls/__init__.py
Normal file
26
polls/admin.py
Normal file
26
polls/admin.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
# Register your models here.
|
||||||
|
|
||||||
|
from .models import Choice, Question
|
||||||
|
|
||||||
|
|
||||||
|
class ChoiceInLine(admin.TabularInline):
|
||||||
|
model = Choice
|
||||||
|
extra = 3
|
||||||
|
|
||||||
|
|
||||||
|
class QuestionAdmin(admin.ModelAdmin):
|
||||||
|
# https://docs.djangoproject.com/en/1.11/intro/tutorial07/
|
||||||
|
search_fields = ['question_text'] # interesting, seems we can then search on this
|
||||||
|
list_filter = ['pub_date']
|
||||||
|
list_display = ('question_text', 'pub_date', 'was_published_recently')
|
||||||
|
fieldsets = [
|
||||||
|
(None, {'fields': ['question_text']}),
|
||||||
|
('Date information', {'fields': ['pub_date']}),
|
||||||
|
]
|
||||||
|
inlines = [ChoiceInLine]
|
||||||
|
|
||||||
|
|
||||||
|
admin.site.register(Question, QuestionAdmin)
|
||||||
|
admin.site.register(Choice)
|
5
polls/apps.py
Normal file
5
polls/apps.py
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class PollsConfig(AppConfig):
|
||||||
|
name = 'polls'
|
38
polls/migrations/0001_initial.py
Normal file
38
polls/migrations/0001_initial.py
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# Generated by Django 1.11 on 2017-04-23 02:39
|
||||||
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='Choice',
|
||||||
|
fields=[
|
||||||
|
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('choice_text', models.CharField(max_length=200)),
|
||||||
|
('votes', models.IntegerField(default=8)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='Question',
|
||||||
|
fields=[
|
||||||
|
('id', models.AutoField(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.AddField(
|
||||||
|
model_name='choice',
|
||||||
|
name='question',
|
||||||
|
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'),
|
||||||
|
),
|
||||||
|
]
|
0
polls/migrations/__init__.py
Normal file
0
polls/migrations/__init__.py
Normal file
29
polls/models.py
Normal file
29
polls/models.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import datetime
|
||||||
|
from django.db import models
|
||||||
|
from django.utils import timezone
|
||||||
|
# from django.utils.encoding import python_2_unicode_compatible
|
||||||
|
# Create your models here.
|
||||||
|
|
||||||
|
|
||||||
|
class Question(models.Model):
|
||||||
|
question_text = models.CharField(max_length=200)
|
||||||
|
pub_date = models.DateTimeField('date published')
|
||||||
|
|
||||||
|
def was_published_recently(self):
|
||||||
|
now = timezone.now()
|
||||||
|
return now - datetime.timedelta(days=1) <= self.pub_date <= now
|
||||||
|
was_published_recently.admin_order_field = 'pub_date'
|
||||||
|
was_published_recently.boolean = True
|
||||||
|
was_published_recently.short_description = 'Published Recently?'
|
||||||
|
|
||||||
|
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=8)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.choice_text
|
BIN
polls/static/polls/images/background.jpg
Normal file
BIN
polls/static/polls/images/background.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 191 KiB |
1
polls/static/polls/images/background.svg
Normal file
1
polls/static/polls/images/background.svg
Normal file
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 7.2 KiB |
21
polls/static/polls/style.css
Normal file
21
polls/static/polls/style.css
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
a {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
li {
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
background: #42275a; /* fallback for old browsers */
|
||||||
|
background: -webkit-linear-gradient(to right, #734b6d, #42275a); /* Chrome 10-25, Safari 5.1-6 */
|
||||||
|
background: linear-gradient(to right, #734b6d, #42275a); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
|
||||||
|
|
||||||
|
}
|
21
polls/templates/polls/detail.html
Normal file
21
polls/templates/polls/detail.html
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
{% load static %}
|
||||||
|
|
||||||
|
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
|
||||||
|
|
||||||
|
<h1>{{ question.question_text }}</h1>
|
||||||
|
|
||||||
|
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
|
||||||
|
|
||||||
|
<form action="{% url 'polls:vote' question.id %}" method="post">
|
||||||
|
{% csrf_token %}
|
||||||
|
{% 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 %}
|
||||||
|
<input type="submit" value="Vote" />
|
||||||
|
</form>
|
||||||
|
<!--<ul>
|
||||||
|
{% for choice in question.choice_set.all %}
|
||||||
|
<li> {{ choice.choice_text}} </li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul> -->
|
16
polls/templates/polls/index.html
Normal file
16
polls/templates/polls/index.html
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
{% load static %}
|
||||||
|
|
||||||
|
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
|
||||||
|
|
||||||
|
{% if last_question_list %}
|
||||||
|
<ul>
|
||||||
|
{% for question in last_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 %}
|
11
polls/templates/polls/results.html
Normal file
11
polls/templates/polls/results.html
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
{% load static %}
|
||||||
|
|
||||||
|
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
|
||||||
|
|
||||||
|
<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>
|
124
polls/tests.py
Normal file
124
polls/tests.py
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
import datetime
|
||||||
|
from django.utils import timezone
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from .models import Question
|
||||||
|
|
||||||
|
|
||||||
|
def create_question(question_text, days):
|
||||||
|
"""
|
||||||
|
Creates a question with the given `question_text` and published the
|
||||||
|
given number of `days` offset to now (negative for questions published
|
||||||
|
in the past, positive for questions that have yet to be published).
|
||||||
|
"""
|
||||||
|
time = timezone.now() + datetime.timedelta(days=days)
|
||||||
|
return Question.objects.create(question_text=question_text, pub_date=time)
|
||||||
|
|
||||||
|
|
||||||
|
class QuestionMethodTests(TestCase):
|
||||||
|
|
||||||
|
def test_was_published_with_future_quetsion(self):
|
||||||
|
"""
|
||||||
|
was_published recently() should be false ofr future dates.
|
||||||
|
"""
|
||||||
|
time = timezone.now() + datetime.timedelta(days=30)
|
||||||
|
future_question = Question(pub_date=time)
|
||||||
|
self.assertIs(future_question.was_published_recently(), False)
|
||||||
|
|
||||||
|
def test_was_published_with_old_quetsion(self):
|
||||||
|
"""
|
||||||
|
was_published_recently() should return false for questions whose
|
||||||
|
pub_date is older than 1 day
|
||||||
|
"""
|
||||||
|
time = timezone.now() - datetime.timedelta(days=30)
|
||||||
|
old_question = Question(pub_date=time)
|
||||||
|
self.assertIs(old_question.was_published_recently(), False)
|
||||||
|
|
||||||
|
def test_was_published_recently_with_recent_question(self):
|
||||||
|
"""
|
||||||
|
was_published_recently() should return true for qeustions
|
||||||
|
whose pub_date is within last day,
|
||||||
|
"""
|
||||||
|
time = timezone.now() - datetime.timedelta(hours=1)
|
||||||
|
recent_question = Question(pub_date=time)
|
||||||
|
self.assertIs(recent_question.was_published_recently(), True)
|
||||||
|
|
||||||
|
class QuestionViewTests(TestCase):
|
||||||
|
def test_idex_view_with_no_questions(self):
|
||||||
|
"""
|
||||||
|
If no questions exist, an appropriate message should be displayed.
|
||||||
|
"""
|
||||||
|
response = self.client.get(reverse('polls:index'))
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertContains(response, "No polls are available.")
|
||||||
|
self.assertQuerysetEqual(response.context['latest_question_list'], [])
|
||||||
|
|
||||||
|
def test_index_view_with_a_past_question(self):
|
||||||
|
"""
|
||||||
|
Questions with a pub_date in the past should be displayed on the
|
||||||
|
index page.
|
||||||
|
"""
|
||||||
|
create_question(question_text="Past question.", days=-30)
|
||||||
|
response = self.client.get(reverse('polls:index'))
|
||||||
|
self.assertQuerysetEqual(
|
||||||
|
response.context['latest_question_list'],
|
||||||
|
['<Question: Past question.>']
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_index_view_with_a_future_question(self):
|
||||||
|
"""
|
||||||
|
Questions with a pub_date in the future should not be displayed on
|
||||||
|
the index page.
|
||||||
|
"""
|
||||||
|
create_question(question_text="Future question.", days=30)
|
||||||
|
response = self.client.get(reverse('polls:index'))
|
||||||
|
self.assertContains(response, "No polls are available.")
|
||||||
|
self.assertQuerysetEqual(response.context['latest_question_list'], [])
|
||||||
|
|
||||||
|
def test_index_view_with_future_question_and_past_question(self):
|
||||||
|
"""
|
||||||
|
Even if both past and future questions exist, only past questions
|
||||||
|
should be displayed.
|
||||||
|
"""
|
||||||
|
create_question(question_text="Past question.", days=-30)
|
||||||
|
create_question(question_text="Future question.", days=30)
|
||||||
|
response = self.client.get(reverse('polls:index'))
|
||||||
|
self.assertQuerysetEqual(
|
||||||
|
response.context['latest_question_list'],
|
||||||
|
['<Question: Past question.>']
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_index_view_with_two_past_questions(self):
|
||||||
|
"""
|
||||||
|
The questions index page may display multiple questions.
|
||||||
|
"""
|
||||||
|
create_question(question_text="Past question 1.", days=-30)
|
||||||
|
create_question(question_text="Past question 2.", days=-5)
|
||||||
|
response = self.client.get(reverse('polls:index'))
|
||||||
|
self.assertQuerysetEqual(
|
||||||
|
response.context['latest_question_list'],
|
||||||
|
['<Question: Past question 2.>', '<Question: Past question 1.>']
|
||||||
|
)
|
||||||
|
|
||||||
|
class QuestionIndexDetailTests(TestCase):
|
||||||
|
|
||||||
|
def test_detail_view_with_a_future_question(self):
|
||||||
|
"""
|
||||||
|
The detail view of a question with a pub_date in the future should
|
||||||
|
return a 404 not found.
|
||||||
|
"""
|
||||||
|
future_question = create_question(question_text='Future question.', days=5)
|
||||||
|
url = reverse('polls:detail', args=(future_question.id,))
|
||||||
|
response = self.client.get(url)
|
||||||
|
self.assertEqual(response.status_code, 404)
|
||||||
|
|
||||||
|
def test_detail_view_with_a_past_question(self):
|
||||||
|
"""
|
||||||
|
The detail view of a question with a pub_date in the past should
|
||||||
|
display the question's text.
|
||||||
|
"""
|
||||||
|
past_question = create_question(question_text='Past Question.', days=-5)
|
||||||
|
url = reverse('polls:detail', args=(past_question.id,))
|
||||||
|
response = self.client.get(url)
|
||||||
|
self.assertContains(response, past_question.question_text)
|
15
polls/urls.py
Normal file
15
polls/urls.py
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
from django.conf.urls import url
|
||||||
|
|
||||||
|
from . import views
|
||||||
|
|
||||||
|
app_name = 'polls'
|
||||||
|
urlpatterns = [
|
||||||
|
url(r'^$', views.index, name='index'),
|
||||||
|
# /polls/5/
|
||||||
|
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
|
||||||
|
# ex: /polls/5/results/
|
||||||
|
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
|
||||||
|
# ex: /polls/5/vote/
|
||||||
|
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
|
||||||
|
|
||||||
|
]
|
106
polls/views.py
Normal file
106
polls/views.py
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
from django.shortcuts import get_object_or_404, render
|
||||||
|
|
||||||
|
# Create your views here.
|
||||||
|
from django.http import HttpResponse, HttpResponseRedirect
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.views import generic
|
||||||
|
# from django.http import Http404
|
||||||
|
# from django.template import loader
|
||||||
|
|
||||||
|
from django.utils import timezone
|
||||||
|
|
||||||
|
from .models import Choice, Question
|
||||||
|
|
||||||
|
|
||||||
|
# def index(request):
|
||||||
|
# return HttpResponse("Hello, world. You're at the polls index.")
|
||||||
|
|
||||||
|
|
||||||
|
# def detail(request, question_id):
|
||||||
|
# return HttpResponse("Youre looking at question %s." % question_id)
|
||||||
|
|
||||||
|
class IndexView(generic.ListView):
|
||||||
|
template_name = 'polls/index.html'
|
||||||
|
context_object_name = 'latest_question_list'
|
||||||
|
|
||||||
|
def get_queryrset(self):
|
||||||
|
"""Return last 5 published polls, not counting future ones"""
|
||||||
|
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
|
||||||
|
|
||||||
|
|
||||||
|
class DetailView(generic.DetailView):
|
||||||
|
model = Question
|
||||||
|
template_name = 'polls/detail.html'
|
||||||
|
|
||||||
|
def get_queryrset(self):
|
||||||
|
"""
|
||||||
|
excludes questions not yet published
|
||||||
|
"""
|
||||||
|
return Question.objects.filter(pub_date__lte=timezone.now())
|
||||||
|
|
||||||
|
|
||||||
|
class ResultsView(generic.DetailView):
|
||||||
|
model = Question
|
||||||
|
template_name = 'polls/results.html'
|
||||||
|
|
||||||
|
|
||||||
|
def results(request, question_id):
|
||||||
|
question = get_object_or_404(Question, pk=question_id)
|
||||||
|
return render(request, 'polls/results.html', {'question': question})
|
||||||
|
# response = "Your looking at the results of question %s."
|
||||||
|
# return HttpResponse(response % question_id)
|
||||||
|
|
||||||
|
|
||||||
|
def votes(request, question_id):
|
||||||
|
return HttpResponse("You are voting on %s." % question_id)
|
||||||
|
|
||||||
|
|
||||||
|
def index(request):
|
||||||
|
last_question_list = Question.objects.order_by('-pub_date')[:5]
|
||||||
|
context = {'last_question_list': last_question_list}
|
||||||
|
return render(request, 'polls/index.html', context)
|
||||||
|
|
||||||
|
# output = ', '.join([q.question_text for q in last_question_list])
|
||||||
|
# return HttpResponse(output)
|
||||||
|
# context = {'last_question_list': last_question_list}
|
||||||
|
# return render(request, 'polls/index.html', context)
|
||||||
|
|
||||||
|
|
||||||
|
def detail(request, question_id):
|
||||||
|
question = get_object_or_404(Question, pk=question_id)
|
||||||
|
return render(request, 'polls/detail.html', {'question': question})
|
||||||
|
|
||||||
|
# doing this new short cut, we don't see the custom wording, how do we do
|
||||||
|
# that?
|
||||||
|
# try:
|
||||||
|
# question = Question.objects.get(pk=question_id)
|
||||||
|
# except Question.DoesNotExist:
|
||||||
|
# raise Http404("Question does not exist")
|
||||||
|
# return render(request, 'polls/detail.html', {'question': question})
|
||||||
|
|
||||||
|
|
||||||
|
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 += 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,)))
|
||||||
|
# return HttpResponse("Your voting on question %s." % question_id)
|
||||||
|
|
||||||
|
# def detail(request, question_id):
|
||||||
|
# try:
|
||||||
|
# question = Question.objects.get(pk=question_id)
|
||||||
|
# except Question.DoesNotExist:
|
||||||
|
# raise Http404("question does not exist")
|
||||||
|
# return render(request, 'polls/detal.html', 'question': question
|
19
readme.md
Normal file
19
readme.md
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
howto:
|
||||||
|
```
|
||||||
|
# create env
|
||||||
|
python3 -m venv venv
|
||||||
|
|
||||||
|
# install deps
|
||||||
|
source venv/bin/activate
|
||||||
|
python -m pip install django
|
||||||
|
|
||||||
|
# bootstrap app
|
||||||
|
python manage.py makemigrations
|
||||||
|
python manage.py migrate
|
||||||
|
|
||||||
|
# create admin user
|
||||||
|
python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'admin123')" 2> /dev/null || true
|
||||||
|
|
||||||
|
# serve app
|
||||||
|
python manage.py runserver 49376
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user