From: Tom Walker Date: Wed, 2 Jul 2014 16:03:49 +0000 (+0100) Subject: pep8 everything X-Git-Url: https://git.parisson.com/?a=commitdiff_plain;h=2847b558de72bdd1352c98628c87dcc65a3b30b5;p=django_quiz.git pep8 everything --- diff --git a/multichoice/models.py b/multichoice/models.py index e80d42c..efbb77f 100644 --- a/multichoice/models.py +++ b/multichoice/models.py @@ -1,13 +1,13 @@ from django.db import models -from quiz.models import Quiz, Category, Question +from quiz.models import Question class MCQuestion(Question): def check_if_correct(self, guess): - answer = Answer.objects.get(id = guess) + answer = Answer.objects.get(id=guess) - if answer.correct == True: + if answer.correct is True: return True else: return False @@ -20,14 +20,14 @@ class MCQuestion(Question): class Answer(models.Model): question = models.ForeignKey(MCQuestion) - content = models.CharField(max_length = 1000, - blank = False, - help_text = ("Enter the answer text that " + - "you want displayed"),) + content = models.CharField(max_length=1000, + blank=False, + help_text="Enter the answer text that " + "you want displayed") - correct = models.BooleanField(blank = False, - default = False, - help_text = "Is this a correct answer?",) + correct = models.BooleanField(blank=False, + default=False, + help_text="Is this a correct answer?") def __unicode__(self): - return self.content + return unicode(self.content) diff --git a/multichoice/tests.py b/multichoice/tests.py index 7fbd5ac..1dd8455 100644 --- a/multichoice/tests.py +++ b/multichoice/tests.py @@ -5,27 +5,26 @@ from multichoice.models import MCQuestion, Answer class TestMCQuestionModel(TestCase): def setUp(self): - self.q = MCQuestion.objects.create(id = 1, - content = ("WHAT is the airspeed" + - "velocity of an unladen" + - "swallow?"), - explanation = "I, I don't know that!",) - - self.answer1 = Answer.objects.create(id = 123, - question = self.q, - content = "African", - correct = False,) - - self.answer2 = Answer.objects.create(id = 456, - question = self.q, - content = "European", - correct = True) - + self.q = MCQuestion.objects.create(id=1, + content=("WHAT is the airspeed" + + "velocity of an unladen" + + "swallow?"), + explanation="I, I don't know that!") + + self.answer1 = Answer.objects.create(id=123, + question=self.q, + content="African", + correct=False) + + self.answer2 = Answer.objects.create(id=456, + question=self.q, + content="European", + correct=True) def test_answers(self): - answers = Answer.objects.filter(question__id = self.q.id) - correct_a = Answer.objects.get(question__id = self.q.id, - correct = True,) + answers = Answer.objects.filter(question__id=self.q.id) + correct_a = Answer.objects.get(question__id=self.q.id, + correct=True) self.assertEqual(answers.count(), 2) self.assertEqual(correct_a.content, "European") diff --git a/quiz/models.py b/quiz/models.py index 517cc23..ddf455e 100644 --- a/quiz/models.py +++ b/quiz/models.py @@ -1,10 +1,5 @@ -import re # uh oh - +import re from django.db import models -from django.conf import settings -from django.utils.encoding import smart_str -from django.contrib.auth.models import User - from model_utils.managers import InheritanceManager # the above taken from: # https://django-model-utils.readthedocs.org/en/latest/managers.html @@ -14,35 +9,34 @@ from model_utils.managers import InheritanceManager If you want to prepopulate the category choices then here is an example. Uncomment 'choices' in the category model. """ -CATEGORY_CHOICES = ( ('Endocrinology', 'Endocrinology'), - ('Dermatology', 'Dermatology'), - ('Cellular Biology', 'Cellular Biology'), - ('Neurology', 'Neurology'), - ('Gastroenterology', 'Gastroenterology'), - ('Statistics', 'Statistics'), - ('Rheumatology', 'Rheumatology'), - ('Tropical medicine', 'Tropical medicine'), - ('Respiratory', 'Respiratory'), - ('Immunology', 'Immunology'), - ('Nephrology', 'Nephrology'), - ('Genetic Medicine', 'Genetic Medicine'), - ('Haematology', 'Haematology'), - ('Pharmacology', 'Pharmacology'), - ('Physiology', 'Physiology'), - ('Ophthalmology', 'Ophthalmology'), - ('Anatomy', 'Anatomy'), - ('Biochemistry', 'Biochemistry'), - ('empty', 'empty'), - ('Psychiatry', 'Psychiatry'), - ('Cardiology', 'Cardiology'), - ) +CATEGORY_CHOICES = (('Endocrinology', 'Endocrinology'), + ('Dermatology', 'Dermatology'), + ('Cellular Biology', 'Cellular Biology'), + ('Neurology', 'Neurology'), + ('Gastroenterology', 'Gastroenterology'), + ('Statistics', 'Statistics'), + ('Rheumatology', 'Rheumatology'), + ('Tropical medicine', 'Tropical medicine'), + ('Respiratory', 'Respiratory'), + ('Immunology', 'Immunology'), + ('Nephrology', 'Nephrology'), + ('Genetic Medicine', 'Genetic Medicine'), + ('Haematology', 'Haematology'), + ('Pharmacology', 'Pharmacology'), + ('Physiology', 'Physiology'), + ('Ophthalmology', 'Ophthalmology'), + ('Anatomy', 'Anatomy'), + ('Biochemistry', 'Biochemistry'), + ('empty', 'empty'), + ('Psychiatry', 'Psychiatry'), + ('Cardiology', 'Cardiology')) class CategoryManager(models.Manager): def new_category(self, category): - new_category = self.create(category = - re.sub('\s+', '-', category).lower()) + new_category = self.create(category=re.sub('\s+', '-', category) + .lower()) new_category.save() return new_category @@ -50,11 +44,11 @@ class CategoryManager(models.Manager): class Category(models.Model): - category = models.CharField(max_length = 250, - blank = True, - # choices = CATEGORY_CHOICES, - unique = True, - null = True,) + category = models.CharField(max_length=250, + blank=True, + # choices=CATEGORY_CHOICES, + unique=True, + null=True) objects = CategoryManager() @@ -63,84 +57,81 @@ class Category(models.Model): verbose_name_plural = "Categories" def __unicode__(self): - return self.category + return unicode(self.category) class Quiz(models.Model): - title = models.CharField(max_length = 60, - blank = False,) + title = models.CharField(max_length=60, + blank=False) - description = models.TextField(blank = True, - help_text = ("a description of the quiz"),) + description = models.TextField(blank=True, + help_text="a description of the quiz") - url = models.CharField(max_length = 60, - blank = False, - help_text = ("a user friendly url"), - verbose_name = ('user friendly url'),) + url = models.SlugField(max_length=60, + blank=False, + help_text="a user friendly url", + verbose_name="user friendly url") category = models.ForeignKey(Category, - null = True, - blank = True,) - - random_order = models.BooleanField(blank = False, - default = False, - help_text = ("Display the questions in \ - a random order or as they \ - are set?"),) - - answers_at_end = models.BooleanField(blank = False, - default = False, - help_text = ("Correct answer is NOT \ - shown after question. \ - Answers displayed at \ - the end"),) - - exam_paper = models.BooleanField(blank = False, - default = False, - help_text = ("If yes, the result of each \ - attempt by a user will be \ - stored"),) - - single_attempt = models.BooleanField(blank = False, - default = False, - help_text = ("If yes, only one \ - attempt by a user will \ - be permitted. Non \ - users cannot sit \ - this exam."),) - - - def save(self, force_insert = False, force_update = False, *args, **kwargs): + null=True, + blank=True) + + random_order = models.BooleanField(blank=False, + default=False, + help_text="Display the questions in " + "a random order or as they " + "are set?") + + answers_at_end = models.BooleanField(blank=False, + default=False, + help_text="Correct answer is NOT" + " shown after question." + " Answers displayed at" + " the end.") + + exam_paper = models.BooleanField(blank=False, + default=False, + help_text="If yes, the result of each" + " attempt by a user will be" + " stored.") + + single_attempt = models.BooleanField(blank=False, + default=False, + help_text="If yes, only one attempt" + " by a user will be" + " permitted. Non users" + " cannot sit this exam.") + + def save(self, force_insert=False, force_update=False, *args, **kwargs): self.url = re.sub('\s+', '-', self.url).lower() self.url = ''.join(letter for letter in self.url if letter.isalnum() or letter == '-') - if self.single_attempt == True: + if self.single_attempt is True: self.exam_paper = True super(Quiz, self).save(force_insert, force_update, *args, **kwargs) - class Meta: verbose_name = "Quiz" verbose_name_plural = "Quizzes" - def __unicode__(self): - return self.title - + return unicode(self.title) """ Progress is used to track an individual signed in users score on different quiz's and categories """ + class ProgressManager(models.Manager): def new_progress(self, user): - new_progress = self.create(user = user, score = '') + new_progress = self.create(user=user, + score="") new_progress.save() return new_progress @@ -153,9 +144,9 @@ class Progress(models.Model): Data stored in csv using the format: category, score, possible, category, score, possible, ... """ - user = models.OneToOneField('auth.User') # one user per progress class + user = models.OneToOneField("auth.User") - score = models.CommaSeparatedIntegerField(max_length = 1024) + score = models.CommaSeparatedIntegerField(max_length=1024) objects = ProgressManager() @@ -189,20 +180,19 @@ class Progress(models.Model): possible = int(match.group(2)) try: - percent = int(round((float(score) / float(possible)) * 100)) + percent = int(round((float(score) / float(possible)) + * 100)) except: percent = 0 score_list = [score, possible, percent] output[cat.category] = score_list - - else: # if category has not been added yet, add it. + else: # if category has not been added yet, add it. temp = self.score + cat.category + ",0,0," self.score = temp output[cat.category] = [0, 0] - if len(self.score) > len(score_before): """ If a new category has been added, save changes. Otherwise nothing @@ -212,17 +202,16 @@ class Progress(models.Model): return output - def check_cat_score(self, category_queried): """ Pass in a category, get the users score and possible maximum score as the integers x,y respectively """ - category_test = Category.objects.filter(category = category_queried) \ + category_test = Category.objects.filter(category=category_queried) \ .exists() - if category_test == False: + if category_test is False: return "error", "category does not exist" to_find = re.escape(category_queried) + r",(\d+),(\d+)," @@ -234,14 +223,13 @@ class Progress(models.Model): possible = int(match.group(2)) return score, possible - else: # if not found but category exists, add category with 0 points + else: # if not found but category exists, add category with 0 points temp = self.score + category_queried + ",0,0," self.score = temp self.save() return 0, 0 - def update_score(self, category_queried, score_to_add, possible_to_add): """ Pass in category, amount to increase score and max possible. @@ -251,13 +239,12 @@ class Progress(models.Model): TO DO: Raise error when necessary """ - - category_test = Category.objects.filter(category = category_queried) \ + category_test = Category.objects.filter(category=category_queried) \ .exists() - if any([category_test == False, score_to_add == False, - possible_to_add == False, str(score_to_add).isdigit() == False, - str(possible_to_add).isdigit() == False]): + if any([category_test is False, score_to_add is False, + possible_to_add is False, str(score_to_add).isdigit() is False, + str(possible_to_add).isdigit() is False]): return "error", "category does not exist or invalid score" to_find = re.escape(str(category_queried)) + r",(\d+),(\d+)," @@ -293,20 +280,19 @@ class Progress(models.Model): self.score = temp self.save() - def show_exams(self): """ Finds the previous quizzes marked as 'exam papers'. Returns a queryset of complete exams. """ - return Sitting.objects.filter(user = self.user) \ - .filter(complete = True) + return Sitting.objects.filter(user=self.user) \ + .filter(complete=True) class SittingManager(models.Manager): def new_sitting(self, user, quiz): - if quiz.random_order == True: + if quiz.random_order is True: question_set = quiz.question_set.all() \ .select_subclasses() \ .order_by('?') @@ -318,12 +304,12 @@ class SittingManager(models.Manager): for question in question_set: questions = (questions + str(question.id) + ",") - new_sitting = self.create(user = user, - quiz = quiz, - question_list = questions, - incorrect_questions = "", - current_score = 0, - complete = False,) + new_sitting = self.create(user=user, + quiz=quiz, + question_list=questions, + incorrect_questions="", + current_score=0, + complete=False) new_sitting.save() return new_sitting @@ -345,14 +331,14 @@ class Sitting(models.Model): quiz = models.ForeignKey(Quiz) - question_list = models.CommaSeparatedIntegerField(max_length = 1024) + question_list = models.CommaSeparatedIntegerField(max_length=1024) - incorrect_questions = models.CommaSeparatedIntegerField(max_length = 1024, - blank = True) + incorrect_questions = models.CommaSeparatedIntegerField(max_length=1024, + blank=True) current_score = models.IntegerField() - complete = models.BooleanField(default = False, blank = False) + complete = models.BooleanField(default=False, blank=False) objects = SittingManager() @@ -368,7 +354,6 @@ class Sitting(models.Model): return int(self.question_list[:first_comma]) - def remove_first_question(self): first_comma = self.question_list.find(',') if first_comma != -1 or first_comma != 0: @@ -409,7 +394,7 @@ class Sitting(models.Model): Adds uid of incorrect question to the list. The question object must be passed in. """ - if isinstance(question, Question) == False: + if isinstance(question, Question) is False: return False current_incorrect = self.incorrect_questions question_id = question.id @@ -429,22 +414,25 @@ class Question(models.Model): Shared properties placed here. """ - quiz = models.ManyToManyField(Quiz, blank = True, ) - - category = models.ForeignKey(Category, blank = True, null = True, ) + quiz = models.ManyToManyField(Quiz, + blank=True) - content = models.CharField(max_length = 1000, - blank = False, - help_text = ("Enter the question text that " + - "you want displayed"), - verbose_name = 'Question',) - - explanation = models.TextField(max_length = 2000, - blank = True, - help_text = ("Explanation to be shown " + - "after the question has " + - "been answered."), - verbose_name = 'Explanation',) + category = models.ForeignKey(Category, + blank=True, + null=True) + + content = models.CharField(max_length=1000, + blank=False, + help_text="Enter the question text that " + "you want displayed", + verbose_name='Question') + + explanation = models.TextField(max_length=2000, + blank=True, + help_text="Explanation to be shown " + "after the question has " + "been answered.", + verbose_name='Explanation') objects = InheritanceManager() @@ -452,4 +440,4 @@ class Question(models.Model): ordering = ['category'] def __unicode__(self): - return self.content + return unicode(self.content) diff --git a/quiz/templatetags/quiz_tags.py b/quiz/templatetags/quiz_tags.py index 811bf7d..c42b134 100644 --- a/quiz/templatetags/quiz_tags.py +++ b/quiz/templatetags/quiz_tags.py @@ -1,14 +1,15 @@ from django import template -from django.shortcuts import get_list_or_404 from multichoice.models import Answer register = template.Library() + @register.inclusion_tag('answers_for_mc_question.html', takes_context=True) def answers_for_mc_question(context, question): answers = Answer.objects.filter(question__id=question.id).order_by('?') - return {'answers': answers,} + return {'answers': answers} + @register.inclusion_tag('correct_answer.html', takes_context=True) def correct_answer(context, previous): @@ -30,11 +31,13 @@ def correct_answer(context, previous): {'correct': q.check_if_correct('F'), 'content': 'False'}] return {'answers': answers, - 'question_type': q.__class__.__name__,} + 'question_type': q.__class__.__name__} @register.inclusion_tag('correct_answer.html', takes_context=True) -def correct_answer_for_all_with_users_incorrect(context, question, incorrect_list): +def correct_answer_for_all_with_users_incorrect(context, + question, + incorrect_list): """ processes the correct answer based on a given question object if the answer is incorrect, informs the user @@ -56,6 +59,7 @@ def correct_answer_for_all_with_users_incorrect(context, question, incorrect_lis return {'answers': answers, 'user_was_incorrect': user_was_incorrect, } + @register.inclusion_tag('user_previous_exam.html', takes_context=True) def user_previous_exam(context, exam): """ diff --git a/quiz/tests.py b/quiz/tests.py index 8bad8a5..0803d11 100644 --- a/quiz/tests.py +++ b/quiz/tests.py @@ -1,24 +1,22 @@ # -*- coding: iso-8859-15 -*- -from django.contrib.auth.models import User, AnonymousUser +from django.contrib.auth.models import User from django.core.urlresolvers import resolve -from django.http import HttpRequest from django.test import TestCase -from django.test.client import Client, RequestFactory from django.template import Template, Context - -from quiz.models import Category, Quiz, Progress, Sitting, Question +from quiz.models import Category, Quiz, Progress, Sitting from quiz.views import quiz_take from multichoice.models import MCQuestion, Answer from true_false.models import TF_Question + class TestCategory(TestCase): def setUp(self): - self.c1 = Category.objects.new_category(category = 'elderberries') - self.c2 = Category.objects.new_category(category = 'straw.berries') - self.c3 = Category.objects.new_category(category = 'black berries') - self.c4 = Category.objects.new_category(category = 'squishy berries') + self.c1 = Category.objects.new_category(category='elderberries') + self.c2 = Category.objects.new_category(category='straw.berries') + self.c3 = Category.objects.new_category(category='black berries') + self.c4 = Category.objects.new_category(category='squishy berries') def test_categories(self): @@ -27,27 +25,27 @@ class TestCategory(TestCase): self.assertEqual(self.c3.category, 'black-berries') self.assertEqual(self.c4.category, 'squishy-berries') + class TestQuiz(TestCase): def setUp(self): - self.c1 = Category.objects.new_category(category = 'elderberries') - - self.quiz1 = Quiz.objects.create(id = 1, - title = 'test quiz 1', - description = 'd1', - url = 'tq1',) - self.quiz2 = Quiz.objects.create(id = 2, - title = 'test quiz 2', - description = 'd2', - url = 't q2',) - self.quiz3 = Quiz.objects.create(id = 3, - title = 'test quiz 3', - description = 'd3', - url = 't q3',) - self.quiz4 = Quiz.objects.create(id = 4, - title = 'test quiz 4', - description = 'd4', - url = 't-!£$%^&*q4',) - + self.c1 = Category.objects.new_category(category='elderberries') + + self.quiz1 = Quiz.objects.create(id=1, + title='test quiz 1', + description='d1', + url='tq1',) + self.quiz2 = Quiz.objects.create(id=2, + title='test quiz 2', + description='d2', + url='t q2',) + self.quiz3 = Quiz.objects.create(id=3, + title='test quiz 3', + description='d3', + url='t q3',) + self.quiz4 = Quiz.objects.create(id=4, + title='test quiz 4', + description='d4', + url='T-!£$%^&*Q4',) def test_quiz_url(self): self.assertEqual(self.quiz1.url, 'tq1') @@ -56,12 +54,12 @@ class TestQuiz(TestCase): self.assertEqual(self.quiz4.url, 't-q4') def test_quiz_options(self): - q5 = Quiz.objects.create(id = 5, - title = 'test quiz 5', - description = 'd5', - url = 'tq5', - category = self.c1, - exam_paper = True,) + q5 = Quiz.objects.create(id=5, + title='test quiz 5', + description='d5', + url='tq5', + category=self.c1, + exam_paper=True,) self.assertEqual(q5.category.category, self.c1.category) self.assertEqual(q5.random_order, False) @@ -77,17 +75,16 @@ class TestQuiz(TestCase): class TestProgress(TestCase): def setUp(self): - self.c1 = Category.objects.new_category(category = 'elderberries') - - self.quiz1 = Quiz.objects.create(id = 1, - title = 'test quiz 1', - description = 'd1', - url = 'tq1',) + self.c1 = Category.objects.new_category(category='elderberries') - self.user = User.objects.create_user(username = 'jacob', - email = 'jacob@jacob.com', - password = 'top_secret') + self.quiz1 = Quiz.objects.create(id=1, + title='test quiz 1', + description='d1', + url='tq1',) + self.user = User.objects.create_user(username='jacob', + email='jacob@jacob.com', + password='top_secret') def test_list_all_empty(self): p1 = Progress.objects.new_progress(self.user) @@ -99,7 +96,7 @@ class TestProgress(TestCase): self.assertIn(self.c1.category, p1.score) - Category.objects.new_category(category = 'cheese') + Category.objects.new_category(category='cheese') p1.list_all_cat_scores() @@ -115,7 +112,7 @@ class TestProgress(TestCase): self.assertEqual(fake_score, ('error', 'category does not exist')) - Category.objects.new_category(category = 'cheese') + Category.objects.new_category(category='cheese') cheese_score = p1.check_cat_score('cheese') self.assertEqual(cheese_score, (0, 0)) @@ -129,7 +126,7 @@ class TestProgress(TestCase): self.assertEqual(elderberry_score, (1, 2)) - Category.objects.new_category(category = 'cheese') + Category.objects.new_category(category='cheese') p1.update_score('cheese', 3, 4) cheese_score = p1.check_cat_score('cheese') @@ -144,22 +141,22 @@ class TestProgress(TestCase): class TestSitting(TestCase): def setUp(self): - self.quiz1 = Quiz.objects.create(id = 1, - title = 'test quiz 1', - description = 'd1', - url = 'tq1',) + self.quiz1 = Quiz.objects.create(id=1, + title='test quiz 1', + description='d1', + url='tq1',) - self.question1 = MCQuestion.objects.create(id = 1, - content = 'squawk',) + self.question1 = MCQuestion.objects.create(id=1, + content='squawk',) self.question1.quiz.add(self.quiz1) - self.question2 = MCQuestion.objects.create(id = 2, - content = 'squeek',) + self.question2 = MCQuestion.objects.create(id=2, + content='squeek',) self.question2.quiz.add(self.quiz1) - self.user = User.objects.create_user(username = 'jacob', - email = 'jacob@jacob.com', - password = 'top_secret') + self.user = User.objects.create_user(username='jacob', + email='jacob@jacob.com', + password='top_secret') self.sitting = Sitting.objects.new_sitting(self.user, self.quiz1) @@ -196,8 +193,8 @@ class TestSitting(TestCase): self.sitting.add_incorrect_question(self.question1) self.assertIn('1', self.sitting.get_incorrect_questions()) - question3 = TF_Question.objects.create(id = 3, - content = 'oink',) + question3 = TF_Question.objects.create(id=3, + content='oink',) self.sitting.add_incorrect_question(question3) self.assertIn('3', self.sitting.get_incorrect_questions()) @@ -214,25 +211,25 @@ class TestSitting(TestCase): Tests relating to views ''' + class TestNonQuestionViews(TestCase): ''' Starting on questions not directly involved with questions. ''' def setUp(self): - self.c1 = Category.objects.new_category(category = 'elderberries') - self.c2 = Category.objects.new_category(category = 'straw.berries') - self.c3 = Category.objects.new_category(category = 'black berries') - - self.quiz1 = Quiz.objects.create(id = 1, - title = 'test quiz 1', - description = 'd1', - url = 'tq1', - category = self.c1) - self.quiz2 = Quiz.objects.create(id = 2, - title = 'test quiz 2', - description = 'd2', - url = 't q2',) - + self.c1 = Category.objects.new_category(category='elderberries') + self.c2 = Category.objects.new_category(category='straw.berries') + self.c3 = Category.objects.new_category(category='black berries') + + self.quiz1 = Quiz.objects.create(id=1, + title='test quiz 1', + description='d1', + url='tq1', + category=self.c1) + self.quiz2 = Quiz.objects.create(id=2, + title='test quiz 2', + description='d2', + url='t q2',) def test_index(self): response = self.client.get('/q/') @@ -264,9 +261,9 @@ class TestNonQuestionViews(TestCase): self.assertContains(response, '1 out of 2') def test_progress_user(self): - self.user = User.objects.create_user(username = 'jacob', - email = 'jacob@jacob.com', - password = 'top_secret') + self.user = User.objects.create_user(username='jacob', + email='jacob@jacob.com', + password='top_secret') self.client.login(username='jacob', password='top_secret') p1 = Progress.objects.new_progress(self.user) @@ -275,38 +272,40 @@ class TestNonQuestionViews(TestCase): self.assertContains(response, 'elderberries') self.assertIn('straw.berries', response.context['cat_scores']) - self.assertEqual([1, 2, 50], response.context['cat_scores']['elderberries']) + self.assertEqual([1, 2, 50], + response.context['cat_scores']['elderberries']) self.assertContains(response, 'var difference = 2 - 1;') self.assertContains(response, 'var correct = 1;') + class TestQuestionViewsAnon(TestCase): def setUp(self): - self.c1 = Category.objects.new_category(category = 'elderberries') + self.c1 = Category.objects.new_category(category='elderberries') - self.quiz1 = Quiz.objects.create(id = 1, - title = 'test quiz 1', - description = 'd1', - url = 'tq1', - category = self.c1) + self.quiz1 = Quiz.objects.create(id=1, + title='test quiz 1', + description='d1', + url='tq1', + category=self.c1) - self.question1 = MCQuestion.objects.create(id = 1, - content = 'squawk',) + self.question1 = MCQuestion.objects.create(id=1, + content='squawk',) self.question1.quiz.add(self.quiz1) - self.question2 = MCQuestion.objects.create(id = 2, - content = 'squeek',) + self.question2 = MCQuestion.objects.create(id=2, + content='squeek',) self.question2.quiz.add(self.quiz1) - self.answer1 = Answer.objects.create(id = 123, - question = self.question1, - content = 'bing', - correct = False,) + self.answer1 = Answer.objects.create(id=123, + question=self.question1, + content='bing', + correct=False,) - self.answer2 = Answer.objects.create(id = 456, - question = self.question2, - content = 'bong', - correct = True,) + self.answer2 = Answer.objects.create(id=456, + question=self.question2, + content='bong', + correct=True,) def test_quiz_take_anon_view_only(self): found = resolve('/q/tq1/') @@ -317,7 +316,7 @@ class TestQuestionViewsAnon(TestCase): response = self.client.get('/q/tq1/') - self.assertContains(response, 'squawk', status_code = 200) + self.assertContains(response, 'squawk', status_code=200) self.assertEqual(self.client.session.get_expiry_age(), 259200) self.assertEqual(self.client.session['1_q_list'], [1, 2]) self.assertEqual(self.client.session['1_score'], 0) @@ -332,10 +331,10 @@ class TestQuestionViewsAnon(TestCase): self.assertTemplateUsed('question.html') session = self.client.session - session.set_expiry(1) # session is set when user first starts a - session.save() # quiz, not on subsequent visits + session.set_expiry(1) # session is set when user first starts a + session.save() # quiz, not on subsequent visits - response2 = self.client.get('/q/tq1/') + self.client.get('/q/tq1/') self.assertEqual(self.client.session.get_expiry_age(), 1) self.assertEqual(self.client.session['1_q_list'], [1, 2]) self.assertEqual(self.client.session['1_score'], 0) @@ -351,9 +350,9 @@ class TestQuestionViewsAnon(TestCase): response = self.client.get('/q/tq1/', {'guess': '123', 'question_id': - self.client.session['1_q_list'][0],}) + self.client.session['1_q_list'][0]}) - self.assertContains(response, 'previous question', status_code = 200) + self.assertContains(response, 'previous question', status_code=200) self.assertContains(response, 'incorrect') self.assertContains(response, 'Explanation:') self.assertContains(response, 'squeek') @@ -363,7 +362,7 @@ class TestQuestionViewsAnon(TestCase): self.assertEqual(response.context['previous'], {'previous_answer': '123', 'previous_outcome': 'incorrect', - 'previous_question': first_question,}) + 'previous_question': first_question}) self.assertTemplateUsed('question.html') second_question = response.context['question'] @@ -371,9 +370,9 @@ class TestQuestionViewsAnon(TestCase): response = self.client.get('/q/tq1/', {'guess': '456', 'question_id': - self.client.session['1_q_list'][0],}) + self.client.session['1_q_list'][0]}) - self.assertContains(response, 'previous question', status_code = 200) + self.assertContains(response, 'previous question', status_code=200) self.assertNotContains(response, 'incorrect') self.assertContains(response, 'Explanation:') self.assertContains(response, 'results') @@ -386,7 +385,7 @@ class TestQuestionViewsAnon(TestCase): self.assertEqual(response.context['previous'], {'previous_answer': '456', 'previous_outcome': 'correct', - 'previous_question': second_question,}) + 'previous_question': second_question}) self.assertTemplateUsed('result.html') # quiz restarts @@ -397,7 +396,7 @@ class TestQuestionViewsAnon(TestCase): response = self.client.get('/q/tq1/', {'guess': '123', 'question_id': - self.client.session['1_q_list'][0],}) + self.client.session['1_q_list'][0]}) self.assertEqual(self.client.session['session_score'], 1) self.assertEqual(self.client.session['session_score_possible'], 3) @@ -410,53 +409,52 @@ class TestQuestionViewsAnon(TestCase): self.assertTemplateUsed('single_complete.html') - class TestQuestionViewsUser(TestCase): def setUp(self): - self.c1 = Category.objects.new_category(category = 'elderberries') - - self.quiz1 = Quiz.objects.create(id = 1, - title = 'test quiz 1', - description = 'd1', - url = 'tq1', - category = self.c1) - - self.quiz2 = Quiz.objects.create(id = 2, - title = 'test quiz 2', - description = 'd2', - url = 'tq2', - category = self.c1, - answers_at_end = True, - exam_paper = True) - - self.user = User.objects.create_user(username = 'jacob', - email = 'jacob@jacob.com', - password = 'top_secret') - - self.question1 = MCQuestion.objects.create(id = 1, - content = 'squawk') + self.c1 = Category.objects.new_category(category='elderberries') + + self.quiz1 = Quiz.objects.create(id=1, + title='test quiz 1', + description='d1', + url='tq1', + category=self.c1) + + self.quiz2 = Quiz.objects.create(id=2, + title='test quiz 2', + description='d2', + url='tq2', + category=self.c1, + answers_at_end=True, + exam_paper=True) + + self.user = User.objects.create_user(username='jacob', + email='jacob@jacob.com', + password='top_secret') + + self.question1 = MCQuestion.objects.create(id=1, + content='squawk') self.question1.quiz.add(self.quiz1) self.question1.quiz.add(self.quiz2) - self.question2 = MCQuestion.objects.create(id = 2, - content = 'squeek') + self.question2 = MCQuestion.objects.create(id=2, + content='squeek') self.question2.quiz.add(self.quiz1) - self.question3 = TF_Question.objects.create(id = 3, - content = 'oink', - correct = True) + self.question3 = TF_Question.objects.create(id=3, + content='oink', + correct=True) self.question3.quiz.add(self.quiz2) - self.answer1 = Answer.objects.create(id = 123, - question = self.question1, - content = 'bing', - correct = False,) + self.answer1 = Answer.objects.create(id=123, + question=self.question1, + content='bing', + correct=False,) - self.answer2 = Answer.objects.create(id = 456, - question = self.question2, - content = 'bong', - correct = True,) + self.answer2 = Answer.objects.create(id=456, + question=self.question2, + content='bong', + correct=True,) def test_quiz_take_user_view_only(self): sittings_before = Sitting.objects.count() @@ -464,7 +462,7 @@ class TestQuestionViewsUser(TestCase): self.client.login(username='jacob', password='top_secret') response = self.client.get('/q/tq1/') - sitting = Sitting.objects.get(quiz = self.quiz1) + sitting = Sitting.objects.get(quiz=self.quiz1) sittings_after = Sitting.objects.count() self.assertEqual(sittings_after, 1) @@ -473,8 +471,10 @@ class TestQuestionViewsUser(TestCase): self.assertEqual(sitting.current_score, 0) self.assertEqual(self.client.session['page_count'], 0) self.assertEqual(response.context['quiz'].id, self.quiz1.id) - self.assertEqual(response.context['question'].content, self.question1.content) - self.assertEqual(response.context['question_type'], self.question1.__class__.__name__) + self.assertEqual(response.context['question'].content, + self.question1.content) + self.assertEqual(response.context['question_type'], + self.question1.__class__.__name__) self.assertEqual(response.context['previous'], {}) self.assertEqual(response.context['show_advert'], False) self.assertTemplateUsed('question.html') @@ -482,18 +482,16 @@ class TestQuestionViewsUser(TestCase): response = self.client.get('/q/tq1/') sittings_after = Sitting.objects.count() - self.assertEqual(sittings_after, 1) # new sitting not made + self.assertEqual(sittings_after, 1) # new sitting not made Sitting.objects.new_sitting(sitting.user, self.quiz1) - sittings_after_doubled = Sitting.objects.count() self.assertEqual(Sitting.objects.count(), 2) response = self.client.get('/q/tq1/') - sitting = Sitting.objects.filter(quiz = self.quiz1)[0] + sitting = Sitting.objects.filter(quiz=self.quiz1)[0] self.assertEqual(sitting.question_list, '1,2,') - def test_quiz_take_user_submit(self): self.client.login(username='jacob', password='top_secret') response = self.client.get('/q/tq1/') @@ -502,18 +500,20 @@ class TestQuestionViewsUser(TestCase): self.assertNotContains(response, 'previous question') self.assertEqual(progress_count, 0) - next_question = Sitting.objects.get(quiz = self.quiz1).get_next_question() + next_question = Sitting.objects.get(quiz=self.quiz1)\ + .get_next_question() response = self.client.get('/q/tq1/', {'guess': '123', 'question_id': - next_question,}) + next_question}) - sitting = Sitting.objects.get(quiz = self.quiz1) + sitting = Sitting.objects.get(quiz=self.quiz1) progress_count = Progress.objects.count() - progress = Progress.objects.get(user = sitting.user).list_all_cat_scores() + progress = Progress.objects.get(user=sitting.user)\ + .list_all_cat_scores() - self.assertContains(response, 'previous question', status_code = 200) + self.assertContains(response, 'previous question', status_code=200) self.assertEqual(sitting.current_score, 0) self.assertEqual(sitting.incorrect_questions, '1,') self.assertEqual(sitting.complete, False) @@ -522,7 +522,8 @@ class TestQuestionViewsUser(TestCase): self.assertEqual(sitting.question_list, '2,') self.assertEqual(self.client.session['page_count'], 1) self.assertIn('123', response.context['previous']['previous_answer']) - self.assertEqual(response.context['question'].content, self.question2.content) + self.assertEqual(response.context['question'].content, + self.question2.content) self.assertTemplateUsed('question.html') response = self.client.get('/q/tq1/', @@ -554,10 +555,9 @@ class TestQuestionViewsUser(TestCase): self.assertContains(response, 'above question incorrectly') self.assertContains(response, 'True') - - sitting = Sitting.objects.get(quiz = self.quiz2, - user = self.user) - progress = Progress.objects.get(user = self.user) + sitting = Sitting.objects.get(quiz=self.quiz2, + user=self.user) + progress = Progress.objects.get(user=self.user) # test that exam_paper = True prevents sitting deletion self.assertEqual(Sitting.objects.count(), 1) @@ -581,51 +581,52 @@ class TestQuestionViewsUser(TestCase): self.assertContains(response, 'only one sitting is permitted.') self.assertTemplateUsed('single_complete.html') + class TestTemplateTags(TestCase): def setUp(self): - self.question1 = MCQuestion.objects.create(id = 1, - content = 'squawk') - - self.answer1 = Answer.objects.create(id = 123, - question = self.question1, - content = 'bing', - correct = False,) - - self.answer2 = Answer.objects.create(id = 456, - question = self.question1, - content = 'bong', - correct = True,) - - self.question2 = TF_Question.objects.create(id = 3, - content = 'oink', - correct = True) - self.quiz1 = Quiz.objects.create(id = 1, - title = 'test quiz 1', - description = 'd1', - url = 'tq1',) + self.question1 = MCQuestion.objects.create(id=1, + content='squawk') + + self.answer1 = Answer.objects.create(id=123, + question=self.question1, + content='bing', + correct=False,) + + self.answer2 = Answer.objects.create(id=456, + question=self.question1, + content='bong', + correct=True,) + + self.question2 = TF_Question.objects.create(id=3, + content='oink', + correct=True) + self.quiz1 = Quiz.objects.create(id=1, + title='test quiz 1', + description='d1', + url='tq1',) self.question1.quiz.add(self.quiz1) self.question2.quiz.add(self.quiz1) - self.user = User.objects.create_user(username = 'jacob', - email = 'jacob@jacob.com', - password = 'top_secret') + self.user = User.objects.create_user(username='jacob', + email='jacob@jacob.com', + password='top_secret') self.sitting = Sitting.objects.new_sitting(self.user, self.quiz1) self.sitting.current_score = 1 def test_answers_mc(self): - template = Template( '{% load quiz_tags %}' + - '{% answers_for_mc_question question %}') + template = Template('{% load quiz_tags %}' + + '{% answers_for_mc_question question %}') context = Context({'question': self.question1}) self.assertTemplateUsed('answers_for_mc_question.html') self.assertIn('bing', template.render(context)) def test_correct_answer_MC(self): - template = Template( '{% load quiz_tags %}' + - '{% correct_answer previous %}') + template = Template('{% load quiz_tags %}' + + '{% correct_answer previous %}') previous_MC = {'previous_answer': 123, 'previous_outcome': 'incorrect', @@ -639,8 +640,8 @@ class TestTemplateTags(TestCase): self.assertIn('your answer', template.render(context)) def test_correct_answer_TF(self): - template = Template( '{% load quiz_tags %}' + - '{% correct_answer previous %}') + template = Template('{% load quiz_tags %}' + + '{% correct_answer previous %}') previous_TF = {'previous_answer': 'T', 'previous_outcome': 'correct', @@ -654,31 +655,31 @@ class TestTemplateTags(TestCase): self.assertNotIn('your answer', template.render(context)) def test_correct_answer_all_anon(self): - template = Template( '{% load quiz_tags %}' + - '{% correct_answer_for_all_with_users_incorrect' + - ' question incorrect_questions %}') + template = Template('{% load quiz_tags %}' + + '{% correct_answer_for_all_with_users_incorrect' + + ' question incorrect_questions %}') - context = Context({'question': self.question1,}) + context = Context({'question': self.question1}) self.assertTemplateUsed('correct_answer.html') self.assertIn('bing', template.render(context)) self.assertNotIn('incorrectly', template.render(context)) def test_correct_answer_all_user(self): - template = Template( '{% load quiz_tags %}' + - '{% correct_answer_for_all_with_users_incorrect ' + - 'question incorrect_questions %}') + template = Template('{% load quiz_tags %}' + + '{% correct_answer_for_all_with_users_incorrect ' + + 'question incorrect_questions %}') context = Context({'question': self.question1, - 'incorrect_questions': '1,'}) + 'incorrect_questions': '1,'}) self.assertTemplateUsed('correct_answer.html') self.assertIn('bing', template.render(context)) self.assertIn('incorrectly', template.render(context)) def test_previous_exam(self): - template = Template( '{% load quiz_tags %}' + - '{% user_previous_exam exam %}') + template = Template('{% load quiz_tags %}' + + '{% user_previous_exam exam %}') context = Context({'exam': self.sitting}) diff --git a/quiz/urls.py b/quiz/urls.py index a1cbc56..4ddf183 100644 --- a/quiz/urls.py +++ b/quiz/urls.py @@ -1,14 +1,14 @@ -from django.conf.urls import patterns, include, url +from django.conf.urls import patterns, url urlpatterns = patterns('', # quiz base url url(r'^$', 'quiz.views.index', - name = 'quiz_index'), + name='quiz_index'), url(r'^category/$', 'quiz.views.list_categories', - name = 'quiz_category_list_all'), + name='quiz_category_list_all'), # quiz category: list quizzes url(r'^category/(?P[\w.-]+)/$', @@ -18,15 +18,14 @@ urlpatterns = patterns('', # progress url(r'^progress/$', 'quiz.views.progress', - name = 'quiz_progress'), + name='quiz_progress'), # passes variable 'quiz_name' to quiz_take view url(r'^(?P[\w-]+)/$', 'quiz.views.quiz_take', - name = 'quiz_start_page'), + name='quiz_start_page'), url(r'^(?P[\w-]+)/take/$', 'quiz.views.quiz_take', - name = 'quiz_question'), - -) + name='quiz_question'), + ) diff --git a/quiz/views.py b/quiz/views.py index 45a98f6..d1e9cab 100644 --- a/quiz/views.py +++ b/quiz/views.py @@ -1,44 +1,42 @@ import random -from django.contrib import auth -from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext from django.shortcuts import get_object_or_404, render, render_to_response from quiz.models import Quiz, Category, Progress, Sitting, Question -from multichoice.models import MCQuestion, Answer -from true_false.models import TF_Question + def index(request): all_quizzes = Quiz.objects.all() return render(request, 'quiz_index.html', - {'quiz_list': all_quizzes,}) + {'quiz_list': all_quizzes}) def list_categories(request): return render(request, 'list_categories.html', - {'categories': Category.objects.all(),}) + {'categories': Category.objects.all()}) def view_category(request, slug): category = get_object_or_404(Category, - category = slug.replace(' ', '-').lower()) - quizzes = Quiz.objects.filter(category = category) + category=slug.replace(' ', '-').lower()) + quizzes = Quiz.objects.filter(category=category) return render(request, 'view_quiz_category.html', {'category': category, - 'quizzes': quizzes,}) + 'quizzes': quizzes}) + def quiz_take(request, quiz_name): - quiz = Quiz.objects.get(url = quiz_name.lower()) + quiz = Quiz.objects.get(url=quiz_name.lower()) - if request.user.is_authenticated() == True: + if request.user.is_authenticated() is True: - if quiz.single_attempt == True: + if quiz.single_attempt is True: try: - single = Sitting.objects.get(user = request.user, - quiz = quiz, - complete = True) + Sitting.objects.get(user=request.user, + quiz=quiz, + complete=True) except Sitting.DoesNotExist: pass except Sitting.MultipleObjectsReturned: @@ -47,17 +45,17 @@ def quiz_take(request, quiz_name): return render(request, 'single_complete.html') try: - previous_sitting = Sitting.objects.get(user = request.user, - quiz = quiz, - complete = False,) + previous_sitting = Sitting.objects.get(user=request.user, + quiz=quiz, + complete=False,) except Sitting.DoesNotExist: return user_new_quiz_session(request, quiz) except Sitting.MultipleObjectsReturned: - previous_sitting = Sitting.objects.filter(user = request.user, - quiz = quiz, - complete = False, + previous_sitting = Sitting.objects.filter(user=request.user, + quiz=quiz, + complete=False, )[0] return user_load_next_question(request, previous_sitting, quiz) @@ -65,9 +63,8 @@ def quiz_take(request, quiz_name): else: return user_load_next_question(request, previous_sitting, quiz) - - else: # anon user - if quiz.single_attempt == True: + else: # anon user + if quiz.single_attempt is True: return render(request, 'single_complete.html') quiz_id = str(quiz.id) q_list = quiz_id + "_q_list" @@ -83,7 +80,7 @@ def new_anon_quiz_session(request, quiz): Sets the session variables when starting a quiz for the first time """ - request.session.set_expiry(259200) # expires after 3 days + request.session.set_expiry(259200) # expires after 3 days questions = quiz.question_set.all().select_subclasses() question_list = [] @@ -91,14 +88,14 @@ def new_anon_quiz_session(request, quiz): # question_list is a list of question IDs, which are integers question_list.append(question.id) - if quiz.random_order == True: + if quiz.random_order is True: random.shuffle(question_list) # session score for anon users request.session[str(quiz.id) + "_score"] = 0 # session list of questions - request.session[str(quiz.id)+ "_q_list"] = question_list + request.session[str(quiz.id) + "_q_list"] = question_list if 'page_count' not in request.session: # session page count, used for adverts on original website @@ -118,7 +115,7 @@ def user_new_quiz_session(request, quiz): def load_anon_next_question(request, quiz): - question_list = request.session[str(quiz.id)+ "_q_list"] + question_list = request.session[str(quiz.id) + "_q_list"] previous = {} if 'guess' in request.GET and request.GET['guess']: @@ -126,10 +123,10 @@ def load_anon_next_question(request, quiz): # returns a dictionary with previous question details previous = question_check_anon(request, quiz) question_list = question_list[1:] - request.session[str(quiz.id)+ "_q_list"] = question_list + request.session[str(quiz.id) + "_q_list"] = question_list request.session['page_count'] = request.session['page_count'] + 1 - if not request.session[str(quiz.id)+ "_q_list"]: + if not request.session[str(quiz.id) + "_q_list"]: # no questions left! return final_result_anon(request, quiz, previous) @@ -144,7 +141,7 @@ def load_anon_next_question(request, quiz): # try: # if request.session['page_count'] > 0 and \ - # request.session['page_count'] % 10 == 0: + # request.session['page_count'] % 10 is 0: # request.session['page_count'] = request.session['page_count'] + 1 # show_advert = True @@ -152,7 +149,7 @@ def load_anon_next_question(request, quiz): # request.session['page_count'] = 0 next_question_id = question_list[0] - next_question = Question.objects.get_subclass(id = next_question_id) + next_question = Question.objects.get_subclass(id=next_question_id) question_type = next_question.__class__.__name__ return render_to_response('question.html', @@ -160,8 +157,8 @@ def load_anon_next_question(request, quiz): 'question': next_question, 'question_type': question_type, 'previous': previous, - 'show_advert': show_advert,}, - context_instance = RequestContext(request)) + 'show_advert': show_advert}, + context_instance=RequestContext(request)) def user_load_next_question(request, sitting, quiz): @@ -174,7 +171,7 @@ def user_load_next_question(request, sitting, quiz): question_ID = sitting.get_next_question() - if question_ID == False: + if question_ID is False: # no questions left return final_result_user(request, sitting, previous) @@ -182,14 +179,14 @@ def user_load_next_question(request, sitting, quiz): # try: # if request.session['page_count'] > 0 and \ - # request.session['page_count'] % 10 == 0: + # request.session['page_count'] % 10 is 0: # request.session['page_count'] = request.session['page_count'] + 1 # show_advert = True # except KeyError: # request.session['page_count'] = 0 - next_question = Question.objects.get_subclass(id = question_ID) + next_question = Question.objects.get_subclass(id=question_ID) question_type = next_question.__class__.__name__ return render_to_response('question.html', @@ -197,8 +194,8 @@ def user_load_next_question(request, sitting, quiz): 'question': next_question, 'question_type': question_type, 'previous': previous, - 'show_advert': show_advert,}, - context_instance = RequestContext(request)) + 'show_advert': show_advert}, + context_instance=RequestContext(request)) def final_result_anon(request, quiz, previous): @@ -206,21 +203,21 @@ def final_result_anon(request, quiz, previous): score = request.session[quiz_id + "_score"] max_score = quiz.question_set.all().select_subclasses().count() percent = int(round((float(score) / max_score) * 100)) - if score == 0: + if score is 0: score = "0" session_score, session_possible = anon_session_score(request) del request.session[quiz_id + "_q_list"] - if quiz.answers_at_end == False: + if quiz.answers_at_end is False: return render_to_response('result.html', {'score': score, 'max_score': max_score, 'percent': percent, 'previous': previous, 'session': session_score, - 'possible': session_possible,}, - context_instance = RequestContext(request)) + 'possible': session_possible}, + context_instance=RequestContext(request)) else: questions = quiz.question_set.all().select_subclasses() return render_to_response('result.html', @@ -229,8 +226,8 @@ def final_result_anon(request, quiz, previous): 'percent': percent, 'questions': questions, 'session': session_score, - 'possible': session_possible,}, - context_instance = RequestContext(request)) + 'possible': session_possible}, + context_instance=RequestContext(request)) def final_result_user(request, sitting, previous): @@ -242,17 +239,17 @@ def final_result_user(request, sitting, previous): sitting.mark_quiz_complete() - if quiz.exam_paper == False: # if we do not plan to store the outcome - sitting.delete() # delete the sitting to free up space + if quiz.exam_paper is False: # if we do not plan to store the outcome + sitting.delete() # delete the sitting to free up space - if quiz.answers_at_end == False: + if quiz.answers_at_end is False: return render_to_response('result.html', {'quiz': quiz, 'score': score, 'max_score': max_score, 'percent': percent, - 'previous': previous,}, - context_instance = RequestContext(request)) + 'previous': previous}, + context_instance=RequestContext(request)) else: questions = quiz.question_set.all().select_subclasses() return render_to_response('result.html', @@ -261,17 +258,17 @@ def final_result_user(request, sitting, previous): 'max_score': max_score, 'percent': percent, 'questions': questions, - 'incorrect_questions': incorrect,}, - context_instance = RequestContext(request)) + 'incorrect_questions': incorrect}, + context_instance=RequestContext(request)) def question_check_anon(request, quiz): guess = request.GET['guess'] question_id = request.GET['question_id'] - question = Question.objects.get_subclass(id = question_id) + question = Question.objects.get_subclass(id=question_id) is_correct = question.check_if_correct(guess) - if is_correct == True: + if is_correct is True: outcome = "correct" current = request.session[str(quiz.id) + "_score"] request.session[str(quiz.id) + "_score"] = int(current) + 1 @@ -281,10 +278,10 @@ def question_check_anon(request, quiz): outcome = "incorrect" anon_session_score(request, 0, 1) - if quiz.answers_at_end != True: + if quiz.answers_at_end is not True: return {'previous_answer': guess, 'previous_outcome': outcome, - 'previous_question': question,} + 'previous_question': question} else: return {} @@ -293,10 +290,10 @@ def question_check_anon(request, quiz): def question_check_user(request, quiz, sitting): guess = request.GET['guess'] question_id = request.GET['question_id'] - question = Question.objects.get_subclass(id = question_id) + question = Question.objects.get_subclass(id=question_id) is_correct = question.check_if_correct(guess) - if is_correct == True: + if is_correct is True: outcome = "correct" sitting.add_to_score(1) user_progress_score_update(request, question.category, 1, 1) @@ -305,17 +302,17 @@ def question_check_user(request, quiz, sitting): sitting.add_incorrect_question(question) user_progress_score_update(request, question.category, 0, 1) - if quiz.answers_at_end != True: + if quiz.answers_at_end is not True: return {'previous_answer': guess, 'previous_outcome': outcome, - 'previous_question': question,} + 'previous_question': question} else: return {} def user_progress_score_update(request, category, score, possible): try: - progress = Progress.objects.get(user = request.user) + progress = Progress.objects.get(user=request.user) except Progress.DoesNotExist: progress = Progress.objects.new_progress(request.user) @@ -323,7 +320,7 @@ def user_progress_score_update(request, category, score, possible): progress.update_score(category, score, possible) -def anon_session_score(request, add = 0, possible = 0): +def anon_session_score(request, add=0, possible=0): """ Returns the session score for non-signed in users. If number passed in then add this to the running total and @@ -340,8 +337,8 @@ def anon_session_score(request, add = 0, possible = 0): request.session["session_score_possible"] = 0 if possible > 0: - request.session["session_score"] = (request.session["session_score"] + \ - add) + request.session["session_score"] = (request.session["session_score"] + + add) request.session["session_score_possible"] = \ (request.session["session_score_possible"] + possible) @@ -351,22 +348,22 @@ def anon_session_score(request, add = 0, possible = 0): def progress(request): - if request.user.is_authenticated() != True: - # display session score and encourage to sign up + if request.user.is_authenticated() is not True: + # display session score and encourage to sign up score, possible = anon_session_score(request) return render_to_response('signup.html', {'anon_score': score, - 'anon_possible': possible,}, - context_instance = RequestContext(request)) + 'anon_possible': possible}, + context_instance=RequestContext(request)) try: - progress = Progress.objects.get(user = request.user) + progress = Progress.objects.get(user=request.user) except Progress.DoesNotExist: progress = Progress.objects.new_progress(request.user) return render_to_response('progress.html', - {'new_user': True,}, - context_instance = RequestContext(request)) + {'new_user': True}, + context_instance=RequestContext(request)) cat_scores = progress.list_all_cat_scores() exams = progress.show_exams() @@ -374,4 +371,4 @@ def progress(request): return render_to_response('progress.html', {'cat_scores': cat_scores, 'exams': exams}, - context_instance = RequestContext(request)) + context_instance=RequestContext(request)) diff --git a/true_false/models.py b/true_false/models.py index 40b74d5..d1e2486 100644 --- a/true_false/models.py +++ b/true_false/models.py @@ -1,12 +1,13 @@ from django.db import models -from quiz.models import Quiz, Category, Question +from quiz.models import Question + class TF_Question(Question): - correct = models.BooleanField(blank = False, - default = False, - help_text = ("Tick this if the question " + - "is true. Leave it blank for" + - " false."),) + correct = models.BooleanField(blank=False, + default=False, + help_text="Tick this if the question " + "is true. Leave it blank for" + " false.") def check_if_correct(self, guess): if guess == "T": @@ -27,4 +28,4 @@ class TF_Question(Question): ordering = ['category'] def __unicode__(self): - return self.content + return unicode(self.content) diff --git a/true_false/tests.py b/true_false/tests.py index 9f2a65d..c9f62bd 100644 --- a/true_false/tests.py +++ b/true_false/tests.py @@ -5,12 +5,12 @@ from true_false.models import TF_Question class TestTrueFalseQuestionModel(TestCase): def setUp(self): - self.red = TF_Question.objects.create(content = "Is red the best colour?", - explanation = "it is", - correct = True,) - self.blue = TF_Question.objects.create(content = "Is blue the best colour?", - explanation = "it is not", - correct = False,) + self.red = TF_Question.objects.create(content="Is red the best?", + explanation="it is", + correct=True,) + self.blue = TF_Question.objects.create(content="Is blue the best?", + explanation="it is not", + correct=False,) def test_true_q(self): self.assertEqual(self.red.correct, True)