Compare commits

...

8 Commits

Author SHA1 Message Date
97dee49b4f
view changes and tests 2022-09-09 09:01:48 +05:30
82b2af8d6b
detail view struggle 2022-09-09 08:41:57 +05:30
2b54e70f1b
add views 2022-09-09 08:28:57 +05:30
2d050c10f4
admin modifiable app 2022-09-09 08:11:44 +05:30
47cf518b3d
test admin user 2022-09-09 08:09:14 +05:30
80f1d1ac95
models and funcs 2022-09-09 08:06:49 +05:30
5af10e2abf
gitignore 2022-09-09 07:51:19 +05:30
f565f2437b
polls 2022-09-09 07:50:35 +05:30
17 changed files with 214 additions and 1 deletions

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
env/
.vscode
__pycache__
db.sqlite3
.env

View File

@ -32,6 +32,7 @@ ALLOWED_HOSTS = []
INSTALLED_APPS = [
"scheduler.apps.SchedulerConfig",
"polls.apps.PollsConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",

View File

@ -18,5 +18,6 @@ from django.urls import include, path
urlpatterns = [
path('scheduler/', include('scheduler.urls')),
path('polls/', include("polls.urls")),
path('admin/', admin.site.urls),
]

Binary file not shown.

View File

5
LCAdmin/polls/admin.py Normal file
View File

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

6
LCAdmin/polls/apps.py Normal file
View File

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

View File

@ -0,0 +1,52 @@
# Generated by Django 4.1 on 2022-09-09 02:24
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"
),
),
],
),
]

View File

22
LCAdmin/polls/models.py Normal file
View File

@ -0,0 +1,22 @@
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 __str__(self):
return self.question_text
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):
return self.choice_text

View File

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

View File

@ -0,0 +1,9 @@
{% 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 %}

View File

@ -0,0 +1,9 @@
<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>

36
LCAdmin/polls/tests.py Normal file
View File

@ -0,0 +1,36 @@
import datetime
from django.test import TestCase
from django.utils import timezone
from .models import Question
class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is in the future.
"""
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_recently_with_old_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is older than 1 day.
"""
time = timezone.now() - datetime.timedelta(days=1, seconds=1)
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() returns True for questions whose pub_date
is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)

11
LCAdmin/polls/urls.py Normal file
View File

@ -0,0 +1,11 @@
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
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'),
]

47
LCAdmin/polls/views.py Normal file
View File

@ -0,0 +1,47 @@
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:
## added type ignore to get rid of choice _set error
selected_choice = question.choice_set.get(pk=request.POST['choice']) # type: ignore
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.
## type ignore bs
return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) # type: ignore # type: ignore)

View File

@ -5,4 +5,4 @@ from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
return HttpResponse("Hello, world. You're at the Scheduler index.")