commit 3dcb765e5b335eeeb56a9907dbf9cb664efc1e40 Author: Artur Tamborski Date: Fri Jun 14 20:41:55 2019 +0200 adddddd diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9583291 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +venv/ +db.sqlite3 +*.pyc diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..df10927 --- /dev/null +++ b/manage.py @@ -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) diff --git a/mysite/__init__.py b/mysite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mysite/settings.py b/mysite/settings.py new file mode 100644 index 0000000..98fe6a3 --- /dev/null +++ b/mysite/settings.py @@ -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/' diff --git a/mysite/urls.py b/mysite/urls.py new file mode 100644 index 0000000..e807a76 --- /dev/null +++ b/mysite/urls.py @@ -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), + ] diff --git a/mysite/wsgi.py b/mysite/wsgi.py new file mode 100644 index 0000000..f3571a1 --- /dev/null +++ b/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/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() diff --git a/polls/__init__.py b/polls/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/polls/admin.py b/polls/admin.py new file mode 100644 index 0000000..99dda6f --- /dev/null +++ b/polls/admin.py @@ -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) diff --git a/polls/apps.py b/polls/apps.py new file mode 100644 index 0000000..c46d01b --- /dev/null +++ b/polls/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class PollsConfig(AppConfig): + name = 'polls' diff --git a/polls/migrations/0001_initial.py b/polls/migrations/0001_initial.py new file mode 100644 index 0000000..e60c074 --- /dev/null +++ b/polls/migrations/0001_initial.py @@ -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'), + ), + ] diff --git a/polls/migrations/__init__.py b/polls/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/polls/models.py b/polls/models.py new file mode 100644 index 0000000..bb00aad --- /dev/null +++ b/polls/models.py @@ -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 diff --git a/polls/static/polls/images/background.jpg b/polls/static/polls/images/background.jpg new file mode 100644 index 0000000..3f67a82 Binary files /dev/null and b/polls/static/polls/images/background.jpg differ diff --git a/polls/static/polls/images/background.svg b/polls/static/polls/images/background.svg new file mode 100644 index 0000000..ff8541c --- /dev/null +++ b/polls/static/polls/images/background.svg @@ -0,0 +1 @@ +TrueThis work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/">Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License</a>.gradient blue green linear dark cyan midnight blue 1920x1080 #008b8b #191970 240°xmple.comgradient blue green linear dark cyan midnight blue 1920x1080 #008b8b #191970 240°gradient blue green linear dark cyan midnight blue 1920x1080 #008b8b #191970 240°© xmple.comxmple.com \ No newline at end of file diff --git a/polls/static/polls/style.css b/polls/static/polls/style.css new file mode 100644 index 0000000..fa2d431 --- /dev/null +++ b/polls/static/polls/style.css @@ -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+ */ + +} diff --git a/polls/templates/polls/detail.html b/polls/templates/polls/detail.html new file mode 100644 index 0000000..56d0159 --- /dev/null +++ b/polls/templates/polls/detail.html @@ -0,0 +1,21 @@ +{% load static %} + + + +

{{ question.question_text }}

+ +{% if error_message %}

{{ error_message }}

{% endif %} + +
+{% csrf_token %} +{% for choice in question.choice_set.all %} + +
+{% endfor %} + +
+ diff --git a/polls/templates/polls/index.html b/polls/templates/polls/index.html new file mode 100644 index 0000000..5f285cb --- /dev/null +++ b/polls/templates/polls/index.html @@ -0,0 +1,16 @@ +{% load static %} + + + +{% if last_question_list %} + + +{% else %} +

No polls are available.

+{% endif %} diff --git a/polls/templates/polls/results.html b/polls/templates/polls/results.html new file mode 100644 index 0000000..385ebfc --- /dev/null +++ b/polls/templates/polls/results.html @@ -0,0 +1,11 @@ +{% load static %} + + + +

{{ question.question_text }}

+ +Vote again? diff --git a/polls/tests.py b/polls/tests.py new file mode 100644 index 0000000..ade0f2d --- /dev/null +++ b/polls/tests.py @@ -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'], + [''] + ) + + 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'], + [''] + ) + + 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'], + ['', ''] + ) + + 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) diff --git a/polls/urls.py b/polls/urls.py new file mode 100644 index 0000000..7e16d66 --- /dev/null +++ b/polls/urls.py @@ -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[0-9]+)/$', views.detail, name='detail'), + # ex: /polls/5/results/ + url(r'^(?P[0-9]+)/results/$', views.results, name='results'), + # ex: /polls/5/vote/ + url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'), + +] diff --git a/polls/views.py b/polls/views.py new file mode 100644 index 0000000..b427617 --- /dev/null +++ b/polls/views.py @@ -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 diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..c275927 --- /dev/null +++ b/readme.md @@ -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 +```