From: Jan Szejko Date: Thu, 3 Mar 2016 15:31:37 +0000 (+0100) Subject: code style X-Git-Url: https://git.mdrn.pl/edumed.git/commitdiff_plain/6c9978c5bf8b1ef20871557c22b8b02df647d700?ds=sidebyside;hp=--cc code style --- 6c9978c5bf8b1ef20871557c22b8b02df647d700 diff --git a/catalogue/admin.py b/catalogue/admin.py index f79b375..8256d66 100755 --- a/catalogue/admin.py +++ b/catalogue/admin.py @@ -1,9 +1,12 @@ +# -*- coding: utf-8 -*- from django.contrib import admin from .models import Attachment, Section, Lesson, LessonStub + class AttachmentInline(admin.TabularInline): model = Attachment + class LessonAdmin(admin.ModelAdmin): inlines = [AttachmentInline] list_display = ['title', 'section', 'type'] @@ -12,4 +15,3 @@ class LessonAdmin(admin.ModelAdmin): admin.site.register(Section) admin.site.register(Lesson, LessonAdmin) admin.site.register(LessonStub) - diff --git a/catalogue/management/commands/importlessons.py b/catalogue/management/commands/importlessons.py index 3bd05ad..e4c09e6 100755 --- a/catalogue/management/commands/importlessons.py +++ b/catalogue/management/commands/importlessons.py @@ -4,27 +4,26 @@ # import os import sys -import time from optparse import make_option -from django.conf import settings + from django.core.management.base import BaseCommand from django.core.management.color import color_style -from django.core.files import File +from django.db import transaction -from librarian import IOFile from catalogue.models import Lesson, Section +from librarian import IOFile -#from search import Index +# from search import Index class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-q', '--quiet', action='store_false', dest='verbose', default=True, - help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'), + help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'), make_option('-a', '--attachments', dest='attachments', metavar="PATH", default='materialy', - help='Attachments dir path.'), + help='Attachments dir path.'), make_option('--ignore-incomplete', action='store_true', dest='ignore_incomplete', default=False, - help='Attachments dir path.'), + help='Attachments dir path.'), ) help = 'Imports lessons from the specified directories.' args = 'directory [directory ...]' @@ -52,9 +51,8 @@ class Command(BaseCommand): read_dir(path) return files - + @transaction.atomic def handle(self, *directories, **options): - from django.db import connection, transaction levels = set() self.style = color_style() @@ -62,17 +60,6 @@ class Command(BaseCommand): verbose = options.get('verbose') self.curdir = os.path.abspath(os.curdir) - - # Start transaction management. - # SQLite will choke on generating thumbnails - use_transaction = not connection.features.autocommits_when_autocommit_is_off - if use_transaction: - transaction.commit_unless_managed() - transaction.enter_transaction_management() - transaction.managed(True) - else: - print 'WARNING: Not using transaction management.' - files_imported = 0 files_skipped = 0 @@ -105,8 +92,9 @@ class Command(BaseCommand): # Import book files try: - lesson = self.import_book(file_path, options, attachments, - ignore_incomplete=file_name in ignore_incomplete) + lesson = self.import_book( + file_path, options, attachments, + ignore_incomplete=file_name in ignore_incomplete) except Section.IncompleteError, e: if file_name not in postponed or postponed[file_name] < files_imported: # Push it back into the queue, maybe the missing lessons will show up. @@ -121,21 +109,18 @@ class Command(BaseCommand): else: # We're in a loop, nothing's being imported - some lesson is really missing. raise e - except BaseException, e: + except BaseException: import traceback traceback.print_exc() files_skipped += 1 else: files_imported += 1 - if use_transaction: - transaction.commit() if hasattr(lesson, 'level'): levels.add(lesson.level) finally: if verbose > 0: print - if levels: print "Rebuilding level packages:" for level in levels: @@ -147,7 +132,3 @@ class Command(BaseCommand): print "Results: %d files imported, %d skipped, %d total." % ( files_imported, files_skipped, files_imported + files_skipped) print - - if use_transaction: - transaction.commit() - transaction.leave_transaction_management() diff --git a/catalogue/management/commands/repackage.py b/catalogue/management/commands/repackage.py index f3ae5e8..a2851f6 100755 --- a/catalogue/management/commands/repackage.py +++ b/catalogue/management/commands/repackage.py @@ -2,7 +2,6 @@ # This file is part of EduMed, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # -from optparse import make_option from django.core.management.base import BaseCommand diff --git a/catalogue/models.py b/catalogue/models.py index 85f0af0..ee07651 100644 --- a/catalogue/models.py +++ b/catalogue/models.py @@ -14,11 +14,11 @@ class Section(models.Model): title = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) order = models.IntegerField() - xml_file = models.FileField(upload_to="catalogue/section/xml", + xml_file = models.FileField( + upload_to="catalogue/section/xml", null=True, blank=True, max_length=255, storage=bofh_storage) - image = models.ImageField(upload_to="catalogue/section/image", - null=True, blank=True) + image = models.ImageField(upload_to="catalogue/section/image", null=True, blank=True) pic = models.ImageField(upload_to="catalogue/section/pic", null=True, blank=True) pic_attribution = models.CharField(max_length=255, null=True, blank=True) @@ -90,17 +90,23 @@ class Lesson(models.Model): curriculum_courses = models.ManyToManyField(CurriculumCourse, blank=True) description = models.TextField(null=True, blank=True) - xml_file = models.FileField(upload_to="catalogue/lesson/xml", + xml_file = models.FileField( + upload_to="catalogue/lesson/xml", null=True, blank=True, max_length=255, storage=bofh_storage) - html_file = models.FileField(upload_to="catalogue/lesson/html", + html_file = models.FileField( + upload_to="catalogue/lesson/html", null=True, blank=True, max_length=255, storage=bofh_storage) - package = models.FileField(upload_to="catalogue/lesson/pack", + package = models.FileField( + upload_to="catalogue/lesson/pack", null=True, blank=True, max_length=255, storage=bofh_storage) - student_package = models.FileField(upload_to="catalogue/lesson/student_pack", + student_package = models.FileField( + upload_to="catalogue/lesson/student_pack", null=True, blank=True, max_length=255, storage=bofh_storage) - pdf = models.FileField(upload_to="catalogue/lesson/pdf", + pdf = models.FileField( + upload_to="catalogue/lesson/pdf", null=True, blank=True, max_length=255, storage=bofh_storage) - student_pdf = models.FileField(upload_to="catalogue/lesson/student_pdf", + student_pdf = models.FileField( + upload_to="catalogue/lesson/student_pdf", null=True, blank=True, max_length=255, storage=bofh_storage) class Meta: @@ -111,7 +117,7 @@ class Lesson(models.Model): @models.permalink def get_absolute_url(self): - return ('catalogue_lesson', [self.slug]) + return 'catalogue_lesson', [self.slug] @classmethod def publish(cls, infile, ignore_incomplete=False): @@ -158,7 +164,8 @@ class Lesson(models.Model): courses = set() for identifier in wldoc.book_info.curriculum: identifier = (identifier or "").replace(' ', '') - if not identifier: continue + if not identifier: + continue try: curr = Curriculum.objects.get(identifier__iexact=identifier) except Curriculum.DoesNotExist: @@ -178,8 +185,8 @@ class Lesson(models.Model): for header in wldoc.edoc.findall('.//naglowek_rozdzial'): if (header.text or '').strip() == lookup: from lxml import etree - self.description = etree.tostring(header.getnext(), - method='text', encoding='unicode').strip() + self.description = etree.tostring( + header.getnext(), method='text', encoding='unicode').strip() self.save() return @@ -199,8 +206,7 @@ class Lesson(models.Model): from .publish import HtmlFormat wldoc = self.wldocument(infile) html = HtmlFormat(wldoc).build() - self.html_file.save("%s.html" % self.slug, - File(open(html.get_filename()))) + self.html_file.save("%s.html" % self.slug, File(open(html.get_filename()))) def build_pdf(self, student=False): from .publish import PdfFormat @@ -209,23 +215,18 @@ class Lesson(models.Model): wldoc = self.wldocument() if student: pdf = PdfFormat(wldoc).build() - self.student_pdf.save("%s.pdf" % self.slug, - File(open(pdf.get_filename()))) + self.student_pdf.save("%s.pdf" % self.slug, File(open(pdf.get_filename()))) else: pdf = PdfFormat(wldoc, teacher=True).build() - self.pdf.save("%s.pdf" % self.slug, - File(open(pdf.get_filename()))) + self.pdf.save("%s.pdf" % self.slug, File(open(pdf.get_filename()))) def add_to_zip(self, zipf, student=False, prefix=''): pdf = self.student_pdf if student else self.pdf if pdf: - zipf.write(pdf.path, - "%s%s%s.pdf" % (prefix, self.slug, "_student" if student else "")) + zipf.write(pdf.path, "%s%s%s.pdf" % (prefix, self.slug, "_student" if student else "")) for attachment in self.attachment_set.all(): - zipf.write(attachment.file.path, - u"%smaterialy/%s.%s" % (prefix, attachment.slug, attachment.ext)) - zipf.write(self.xml_file.path, - "%spliki-zrodlowe/%s.xml" % (prefix, self.slug)) + zipf.write(attachment.file.path, u"%smaterialy/%s.%s" % (prefix, attachment.slug, attachment.ext)) + zipf.write(self.xml_file.path, "%spliki-zrodlowe/%s.xml" % (prefix, self.slug)) def build_package(self, student=False): from StringIO import StringIO @@ -241,17 +242,20 @@ class Lesson(models.Model): ContentFile(buff.getvalue())) def get_syntetic(self): - if self.section is None: return None + if self.section is None: + return None return self.section.syntetic_lesson(self.level) def get_other_level(self): - if self.section is None: return None + if self.section is None: + return None other_levels = self.section.lesson_set.exclude(level=self.level) if other_levels.exists(): return other_levels[0].level def get_previous(self): - if self.section is None: return None + if self.section is None: + return None try: return self.section.lesson_set.filter( type=self.type, level=self.level, @@ -260,7 +264,8 @@ class Lesson(models.Model): return None def get_next(self): - if self.section is None: return None + if self.section is None: + return None try: return self.section.lesson_set.filter( type=self.type, level=self.level, @@ -288,10 +293,8 @@ class Attachment(models.Model): class Part(models.Model): lesson = models.ForeignKey(Lesson) - pdf = models.FileField(upload_to="catalogue/part/pdf", - null=True, blank=True) - student_pdf = models.FileField(upload_to="catalogue/part/student_pdf", - null=True, blank=True) + pdf = models.FileField(upload_to="catalogue/part/pdf", null=True, blank=True) + student_pdf = models.FileField(upload_to="catalogue/part/student_pdf", null=True, blank=True) class LessonStub(models.Model): diff --git a/catalogue/publish.py b/catalogue/publish.py index cca25de..89c76a1 100755 --- a/catalogue/publish.py +++ b/catalogue/publish.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -from django.core.files.base import ContentFile from django.core.files import File from django.core.urlresolvers import reverse from librarian import DocProvider, IOFile @@ -12,15 +11,14 @@ from fnpdjango.utils.text.slughifi import slughifi # TODO: Using sorl.thumbnail for now, # but this should be done in Librarian, # directly using convert or PIL as a fallback. -def get_image(src_img_path, width=None, - default_width=1600, formats=('PNG', 'JPEG', 'GIF')): +def get_image(src_img_path, width=None, default_width=1600, formats=('PNG', 'JPEG', 'GIF')): """ Returns an object with `url` and `storage` attributes, or None if using the original image is OK. """ - + from PIL import Image from sorl.thumbnail import get_thumbnail - + # Does it need converting? # Yes, if width is given explicitly. convert = width is not None @@ -81,8 +79,7 @@ class HtmlFormat(EduModuleFormat): src_img = self.find_attachment(slug, fmt).file except self.MaterialNotFound: return '' - img = get_image(src_img.path, width, - self.DEFAULT_IMAGE_WIDTH, self.IMAGE_FORMATS) + img = get_image(src_img.path, width, self.DEFAULT_IMAGE_WIDTH, self.IMAGE_FORMATS) return (img or src_img).url def text_to_anchor(self, text): @@ -108,10 +105,10 @@ class PdfFormat(EduModulePDFFormat): def get_image(self, name): src_img = super(PdfFormat, self).get_image(name) - img = get_image(src_img.get_filename(), - default_width=self.DEFAULT_IMAGE_WIDTH, - formats=self.IMAGE_FORMATS - ) + img = get_image( + src_img.get_filename(), + default_width=self.DEFAULT_IMAGE_WIDTH, + formats=self.IMAGE_FORMATS) if img: return IOFile.from_filename(img.storage.path(img)) else: diff --git a/catalogue/search_indexes.py b/catalogue/search_indexes.py index 3179efb..035ce98 100755 --- a/catalogue/search_indexes.py +++ b/catalogue/search_indexes.py @@ -1,4 +1,4 @@ -import datetime +# -*- coding: utf-8 -*- from haystack import indexes from .models import Lesson diff --git a/catalogue/templatetags/catalogue_tags.py b/catalogue/templatetags/catalogue_tags.py index eecf9dc..b74224d 100755 --- a/catalogue/templatetags/catalogue_tags.py +++ b/catalogue/templatetags/catalogue_tags.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from collections import defaultdict from django import template from django.utils.datastructures import SortedDict @@ -14,24 +15,21 @@ def catalogue_carousel(): "object_list": Section.objects.all() } + @register.inclusion_tag("catalogue/snippets/levels_main.html") def catalogue_levels_main(): object_list = Level.objects.exclude(lesson=None) c = object_list.count() return { 'object_list': object_list, - #'section_width': (700 - 20 * (c - 1)) / c, + # 'section_width': (700 - 20 * (c - 1)) / c, 'section_width': (700 - 20 * 2) / 3 } @register.inclusion_tag("catalogue/snippets/level_box.html") def level_box(level): - lessons = dict( - synthetic = [], - course = SortedDict(), - project = [], - ) + lessons = {'synthetic': [], 'course': SortedDict(), 'project': []} by_course = defaultdict(lambda: defaultdict(list)) lesson_lists = [alist for alist in [ @@ -49,7 +47,8 @@ def level_box(level): if lesson.section not in lessons['course']: lessons['course'][lesson.section] = [] lessons['course'][lesson.section].append(lesson) - elif lesson.type.startswith('added'): continue + elif lesson.type.startswith('added'): + continue else: lessons[lesson.type].append(lesson) @@ -57,8 +56,8 @@ def level_box(level): for course in lesson.curriculum_courses.all(): by_course[course][lesson.type].append(lesson) - courses = [(course, by_course[course]) for course in - CurriculumCourse.objects.filter(lesson__level=level).distinct()] + courses = [(course, by_course[course]) + for course in CurriculumCourse.objects.filter(lesson__level=level).distinct()] added = [] if level.slug == 'liceum': @@ -67,37 +66,35 @@ def level_box(level): 'title': u'Edukacja filmowa', 'lessons': [ Lesson.objects.get(slug=s) for s in [ -'film-co-to-wlasciwie-jest', -'scenariusz-scenopis-i-srodki-realizacyjne', -'kompozycja-obrazu-filmowego', -'praca-kamery-kadr-kat', -'montaz-materialu-filmowego', -'swiatlo-i-dzwiek-w-filmie', -'scenografia-charakteryzacja-kostiumy-i-aktorzy', -'narracja-w-filmie-tekst-i-fabula', + 'film-co-to-wlasciwie-jest', + 'scenariusz-scenopis-i-srodki-realizacyjne', + 'kompozycja-obrazu-filmowego', + 'praca-kamery-kadr-kat', + 'montaz-materialu-filmowego', + 'swiatlo-i-dzwiek-w-filmie', + 'scenografia-charakteryzacja-kostiumy-i-aktorzy', + 'narracja-w-filmie-tekst-i-fabula', ] ], - }) + }) added.append({ 'slug': 'varsaviana', 'title': u'Edukacja varsavianistyczna', 'lessons': [ - Lesson.objects.get(slug=s) for s in -''' -czego-prus-w-lalce-o-zydach-nie-powiedzial -jak-zmienila-sie-warszawa-o-dworcu-dawniej-i-dzis -o-gwarze-praskiej -poznaj-i-pokaz-prage -praga-trzech-religii -sladami-zydow-w-warszawie -tajemnice-palacu-saskiego -warszawa-przedwojenne-miasto-neonow -warszawski-barok -ziemianska-jako-soczewka-swiata-lat-miedzywojennych -'''.strip().split() + Lesson.objects.get(slug=s) for s in [ + 'czego-prus-w-lalce-o-zydach-nie-powiedzial', + 'jak-zmienila-sie-warszawa-o-dworcu-dawniej-i-dzis', + 'o-gwarze-praskiej', + 'poznaj-i-pokaz-prage', + 'praga-trzech-religii', + 'sladami-zydow-w-warszawie', + 'tajemnice-palacu-saskiego', + 'warszawa-przedwojenne-miasto-neonow', + 'warszawski-barok', + 'ziemianska-jako-soczewka-swiata-lat-miedzywojennych', + ] ], - }) - + }) return { "level": level, @@ -106,6 +103,7 @@ ziemianska-jako-soczewka-swiata-lat-miedzywojennych "added": added, } + @register.inclusion_tag("catalogue/snippets/lesson_nav.html") def lesson_nav(lesson): if lesson.type == 'course': @@ -118,14 +116,14 @@ def lesson_nav(lesson): root = None siblings = [ Lesson.objects.get(slug=s) for s in [ -'film-co-to-wlasciwie-jest', -'scenariusz-scenopis-i-srodki-realizacyjne', -'kompozycja-obrazu-filmowego', -'praca-kamery-kadr-kat', -'montaz-materialu-filmowego', -'swiatlo-i-dzwiek-w-filmie', -'scenografia-charakteryzacja-kostiumy-i-aktorzy', -'narracja-w-filmie-tekst-i-fabula', + 'film-co-to-wlasciwie-jest', + 'scenariusz-scenopis-i-srodki-realizacyjne', + 'kompozycja-obrazu-filmowego', + 'praca-kamery-kadr-kat', + 'montaz-materialu-filmowego', + 'swiatlo-i-dzwiek-w-filmie', + 'scenografia-charakteryzacja-kostiumy-i-aktorzy', + 'narracja-w-filmie-tekst-i-fabula', ] ] else: @@ -137,6 +135,7 @@ def lesson_nav(lesson): "siblings": siblings, } + @register.inclusion_tag("catalogue/snippets/lesson_link.html") def lesson_link(uri): try: @@ -144,6 +143,7 @@ def lesson_link(uri): except Lesson.DoesNotExist: return {} + @register.filter def person_list(persons): return u", ".join(Person.from_text(p).readable() for p in persons) @@ -152,6 +152,8 @@ def person_list(persons): # FIXME: Move to fnpdjango import feedparser import datetime + + @register.inclusion_tag('catalogue/latest_blog_posts.html') def latest_blog_posts(feed_url, posts_to_show=5): try: @@ -159,7 +161,7 @@ def latest_blog_posts(feed_url, posts_to_show=5): posts = [] for i in range(posts_to_show): pub_date = feed['entries'][i].updated_parsed - published = datetime.date(pub_date[0], pub_date[1], pub_date[2] ) + published = datetime.date(pub_date[0], pub_date[1], pub_date[2]) posts.append({ 'title': feed['entries'][i].title, 'summary': feed['entries'][i].summary, diff --git a/catalogue/tests.py b/catalogue/tests.py index 501deb7..b967c44 100644 --- a/catalogue/tests.py +++ b/catalogue/tests.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- """ This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". diff --git a/catalogue/urls.py b/catalogue/urls.py index 3923f61..f2a8b08 100755 --- a/catalogue/urls.py +++ b/catalogue/urls.py @@ -1,7 +1,9 @@ -from django.conf.urls import patterns, include, url +# -*- coding: utf-8 -*- +from django.conf.urls import patterns, url from .views import LessonListView, LessonView -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^$', LessonListView.as_view(), name="catalogue_lessons"), diff --git a/catalogue/views.py b/catalogue/views.py index 0ce7454..4f9d78c 100644 --- a/catalogue/views.py +++ b/catalogue/views.py @@ -1,9 +1,9 @@ -import os.path -from django.conf import settings +# -*- coding: utf-8 -*- from django.views.generic import DetailView, ListView -from .models import Lesson, Section + from curriculum.models import Level from publishers.models import Publisher +from .models import Lesson class LessonListView(ListView): @@ -30,6 +30,6 @@ class LessonView(DetailView): try: context['publisher'] = Publisher.objects.get( name=context['object'].dc.get('publisher', '').strip()) - except: + except (Publisher.DoesNotExist, Publisher.MultipleObjectsReturned): pass return context diff --git a/chunks/admin.py b/chunks/admin.py index 614e4e8..5bdbddc 100644 --- a/chunks/admin.py +++ b/chunks/admin.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django.contrib import admin from chunks.models import Chunk, Attachment @@ -14,4 +15,4 @@ class AttachmentAdmin(admin.ModelAdmin): list_display = ('key',) search_fields = ('key',) -admin.site.register(Attachment, AttachmentAdmin) \ No newline at end of file +admin.site.register(Attachment, AttachmentAdmin) diff --git a/chunks/models.py b/chunks/models.py index ef244eb..5cd007d 100644 --- a/chunks/models.py +++ b/chunks/models.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django.core.cache import cache from django.db import models from django.utils.translation import ugettext_lazy as _ @@ -8,7 +9,8 @@ class Chunk(models.Model): A Chunk is a piece of content associated with a unique key that can be inserted into any template with the use of a special template tag. """ - key = models.CharField(_('key'), help_text=_('A unique name for this chunk of content'), primary_key=True, max_length=255) + key = models.CharField( + _('key'), help_text=_('A unique name for this chunk of content'), primary_key=True, max_length=255) description = models.CharField(_('description'), blank=True, max_length=255) content = models.TextField(_('content'), blank=True) @@ -39,4 +41,3 @@ class Attachment(models.Model): def __unicode__(self): return self.key - diff --git a/chunks/templatetags/chunks.py b/chunks/templatetags/chunks.py index fd24b02..968d284 100644 --- a/chunks/templatetags/chunks.py +++ b/chunks/templatetags/chunks.py @@ -1,5 +1,5 @@ +# -*- coding: utf-8 -*- from django import template -from django.db import models from django.core.cache import cache from ..models import Chunk, Attachment @@ -34,5 +34,3 @@ def attachment(key, cache_time=0): return c.attachment.url except Attachment.DoesNotExist: return '' - - diff --git a/comment/admin.py b/comment/admin.py index 8b3cbd5..7c9ce9a 100644 --- a/comment/admin.py +++ b/comment/admin.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django.contrib import admin from .models import CommentDocument diff --git a/comment/models.py b/comment/models.py index 4cbabfa..38c43d1 100644 --- a/comment/models.py +++ b/comment/models.py @@ -1,13 +1,14 @@ +# -*- coding: utf-8 -*- from django.db import models from django.core.urlresolvers import reverse class CommentDocument(models.Model): - name = models.CharField(max_length = 255, unique = True) - slug = models.SlugField(max_length = 255, unique = True) - comment_id = models.CharField(max_length = 255, unique = True) + name = models.CharField(max_length=255, unique=True) + slug = models.SlugField(max_length=255, unique=True) + comment_id = models.CharField(max_length=255, unique=True) order = models.IntegerField() - language_code = models.CharField(max_length = 2, default = 'pl') + language_code = models.CharField(max_length=2, default='pl') class Meta: ordering = ['order'] @@ -16,4 +17,4 @@ class CommentDocument(models.Model): return self.name def get_absolute_url(self): - return reverse('comment_document', kwargs = dict(slug = self.slug)) + return reverse('comment_document', kwargs={'slug': self.slug}) diff --git a/comment/urls.py b/comment/urls.py index fcc7d99..ef48089 100644 --- a/comment/urls.py +++ b/comment/urls.py @@ -1,9 +1,11 @@ -from django.conf.urls import patterns, include, url +# -*- coding: utf-8 -*- +from django.conf.urls import patterns, url from .views import CommentDocumentList, CommentDocument -urlpatterns = patterns('', - url('^$', CommentDocumentList.as_view(), name = 'comment_document_index'), - url('^(?P[^/]+)/$', CommentDocument.as_view(), name = 'comment_document') -) \ No newline at end of file +urlpatterns = patterns( + '', + url('^$', CommentDocumentList.as_view(), name='comment_document_index'), + url('^(?P[^/]+)/$', CommentDocument.as_view(), name='comment_document') +) diff --git a/comment/views.py b/comment/views.py index 1471029..c7bd9fb 100644 --- a/comment/views.py +++ b/comment/views.py @@ -1,26 +1,27 @@ +# -*- coding: utf-8 -*- from django.views.generic import ListView, DetailView from django.conf import settings from django.utils.translation import get_language from django.core.urlresolvers import reverse -from .models import CommentDocument +from .models import CommentDocument as CommentDocumentModel class CommentDocumentList(ListView): model = CommentDocument - def get_queryset(self, **kwargs): - return super(CommentDocumentList, self).get_queryset(**kwargs).filter(language_code = get_language()) + def get_queryset(self): + return super(CommentDocumentList, self).get_queryset().filter(language_code=get_language()) def get_context_data(self, **kwargs): context = super(CommentDocumentList, self).get_context_data(**kwargs) - context['form_href'] = reverse('contact_form', kwargs = dict(form_tag = 'mil')) + context['form_href'] = reverse('contact_form', kwargs={'form_tag': 'mil'}) return context class CommentDocument(DetailView): - model = CommentDocument + model = CommentDocumentModel def get_context_data(self, **kwargs): context = super(CommentDocument, self).get_context_data(**kwargs) diff --git a/contact/__init__.py b/contact/__init__.py index 0f043ed..3bce2e3 100644 --- a/contact/__init__.py +++ b/contact/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- """ Generic app for creating contact forms. diff --git a/contact/admin.py b/contact/admin.py index 641770e..bb43881 100644 --- a/contact/admin.py +++ b/contact/admin.py @@ -1,9 +1,8 @@ +# -*- coding: utf-8 -*- from django.contrib import admin -from django.forms import ModelForm from .models import Contact from django.utils.translation import ugettext as _ from .forms import contact_forms, admin_list_width -from django.template import Template from django.utils.safestring import mark_safe from django.conf.urls import patterns, url from django.http import HttpResponse, Http404 @@ -15,7 +14,7 @@ class ContactAdminMeta(admin.ModelAdmin.__class__): def __getattr__(cls, name): if name.startswith('admin_list_'): return lambda self: "" - raise AttributeError, name + raise AttributeError(name) class ContactAdmin(admin.ModelAdmin): @@ -27,10 +26,11 @@ class ContactAdmin(admin.ModelAdmin): readonly_fields = ['form_tag', 'created_at', 'contact', 'ip'] list_filter = ['form_tag'] - def admin_list(self, obj, nr): + @staticmethod + def admin_list(obj, nr): try: field_name = contact_forms[obj.form_tag].admin_list[nr] - except BaseException, e: + except BaseException: return '' else: return Contact.pretty_print(obj.body.get(field_name, ''), for_html=True) @@ -39,9 +39,9 @@ class ContactAdmin(admin.ModelAdmin): if name.startswith('admin_list_'): nr = int(name[len('admin_list_'):]) return lambda obj: self.admin_list(obj, nr) - raise AttributeError, name + raise AttributeError(name) - def change_view(self, request, object_id, extra_context=None): + def change_view(self, request, object_id, from_url='', extra_context=None): if object_id: try: instance = Contact.objects.get(pk=object_id) @@ -91,21 +91,25 @@ class ContactAdmin(admin.ModelAdmin): f = (lambda v: lambda self: v)(link) f.short_description = orig_fields[k].label if k in orig_fields else _(k) setattr(self, "body__%s" % k, f) - return super(ContactAdmin, self).change_view(request, object_id, - extra_context=extra_context) + return super(ContactAdmin, self).change_view( + request, object_id, from_url=from_url, extra_context=extra_context) def changelist_view(self, request, extra_context=None): context = dict() if 'form_tag' in request.GET: form = contact_forms.get(request.GET['form_tag']) - context['extract_types'] = [dict(slug = 'all', label = _('all'))] + [dict(slug = 'contacts', label = _('contacts'))] + context['extract_types'] = [ + {'slug': 'all', 'label': _('all')}, + {'slug': 'contacts', 'label': _('contacts')}] context['extract_types'] += [type for type in getattr(form, 'extract_types', [])] - return super(ContactAdmin, self).changelist_view(request, extra_context = context) + return super(ContactAdmin, self).changelist_view(request, extra_context=context) def get_urls(self): - urls = super(ContactAdmin, self).get_urls() - return patterns('', - url(r'^extract/(?P[\w-]+)/(?P[\w-]+)/$', self.admin_site.admin_view(extract_view), name='contact_extract') + # urls = super(ContactAdmin, self).get_urls() + return patterns( + '', + url(r'^extract/(?P[\w-]+)/(?P[\w-]+)/$', + self.admin_site.admin_view(extract_view), name='contact_extract') ) + super(ContactAdmin, self).get_urls() @@ -116,13 +120,13 @@ def extract_view(request, form_tag, extract_type_slug): if form is None and extract_type_slug not in ('contacts', 'all'): raise Http404 - q = Contact.objects.filter(form_tag = form_tag) + q = Contact.objects.filter(form_tag=form_tag) at_year = request.GET.get('created_at__year') at_month = request.GET.get('created_at__month') if at_year: - q = q.filter(created_at__year = at_year) + q = q.filter(created_at__year=at_year) if at_month: - q = q.filter(created_at__month = at_month) + q = q.filter(created_at__month=at_month) # Segregate contacts by body key sets for contact in q.all(): @@ -141,7 +145,7 @@ def extract_view(request, form_tag, extract_type_slug): if extract_type_slug == 'contacts': records = [dict(contact=contact.contact)] elif extract_type_slug == 'all': - records = [dict(contact = contact.contact, **contact.body)] + records = [dict(contact=contact.contact, **contact.body)] else: records = form.get_extract_records(keys, contact, extract_type_slug) @@ -153,7 +157,7 @@ def extract_view(request, form_tag, extract_type_slug): toret += u','.join([record[key] for key in keys]) + '\n' toret += '\n\n' - response = HttpResponse(toret, content_type = 'text/csv') + response = HttpResponse(toret, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="kontakt.csv"' return response diff --git a/contact/forms.py b/contact/forms.py index aab883d..2cea310 100644 --- a/contact/forms.py +++ b/contact/forms.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django.contrib.sites.models import Site from django.core.exceptions import ValidationError from django.core.files.uploadedfile import UploadedFile @@ -11,10 +12,12 @@ from django.utils.translation import ugettext_lazy as _ contact_forms = {} admin_list_width = 0 + + class ContactFormMeta(forms.Form.__class__): - def __new__(cls, *args, **kwargs): + def __new__(cls, name, bases, attrs): global admin_list_width - model = super(ContactFormMeta, cls).__new__(cls, *args, **kwargs) + model = super(ContactFormMeta, cls).__new__(cls, name, bases, attrs) assert model.form_tag not in contact_forms, 'Duplicate form_tag.' if model.admin_list: admin_list_width = max(admin_list_width, len(model.admin_list)) @@ -50,10 +53,11 @@ class ContactForm(forms.Form): if sub_body: body.setdefault(f.form_tag, []).append(sub_body) - contact = Contact.objects.create(body=body, - ip=request.META['REMOTE_ADDR'], - contact=self.cleaned_data['contact'], - form_tag=self.form_tag) + contact = Contact.objects.create( + body=body, + ip=request.META['REMOTE_ADDR'], + contact=self.cleaned_data['contact'], + form_tag=self.form_tag) for name, value in self.cleaned_data.items(): if isinstance(value, UploadedFile): attachment = Attachment(contact=contact, tag=name) @@ -76,8 +80,7 @@ class ContactForm(forms.Form): 'contact/%s/mail_managers_body.txt' % self.form_tag, 'contact/mail_managers_body.txt', ], dictionary, context) - mail_managers(mail_managers_subject, mail_managers_body, - fail_silently=True) + mail_managers(mail_managers_subject, mail_managers_body, fail_silently=True) try: validate_email(contact.contact) @@ -92,9 +95,6 @@ class ContactForm(forms.Form): 'contact/%s/mail_body.txt' % self.form_tag, 'contact/mail_body.txt', ], dictionary, context) - send_mail(mail_subject, mail_body, - 'no-reply@%s' % site.domain, - [contact.contact], - fail_silently=True) + send_mail(mail_subject, mail_body, 'no-reply@%s' % site.domain, [contact.contact], fail_silently=True) return contact diff --git a/contact/models.py b/contact/models.py index f23fddf..1c92610 100644 --- a/contact/models.py +++ b/contact/models.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- import yaml -from django.core.files.storage import FileSystemStorage from django.db import models from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ @@ -18,9 +17,7 @@ class Contact(models.Model): @staticmethod def pretty_print(value, for_html=False): if type(value) in (tuple, list, dict): - value = yaml.safe_dump(value, - allow_unicode=True, - default_flow_style=False) + value = yaml.safe_dump(value, allow_unicode=True, default_flow_style=False) if for_html: value = smart_unicode(value).replace(u" ", unichr(160)) return value @@ -41,7 +38,7 @@ class Attachment(models.Model): @models.permalink def get_absolute_url(self): - return ('contact_attachment', [self.contact_id, self.tag]) + return 'contact_attachment', [self.contact_id, self.tag] __import__(app_settings.FORMS_MODULE) diff --git a/contact/templatetags/contact_tags.py b/contact/templatetags/contact_tags.py index e84064a..aadba16 100755 --- a/contact/templatetags/contact_tags.py +++ b/contact/templatetags/contact_tags.py @@ -1,8 +1,10 @@ +# -*- coding: utf-8 -*- from django.template import Library from contact.models import Contact register = Library() + @register.filter def pretty_print(value): return Contact.pretty_print(value) diff --git a/contact/urls.py b/contact/urls.py index 7f8d4c4..16033a1 100644 --- a/contact/urls.py +++ b/contact/urls.py @@ -1,9 +1,10 @@ +# -*- coding: utf-8 -*- from django.conf.urls import patterns, url from . import views -urlpatterns = patterns('contact.views', +urlpatterns = patterns( + 'contact.views', url(r'^(?P[^/]+)/$', views.form, name='contact_form'), url(r'^(?P[^/]+)/thanks/$', views.thanks, name='contact_thanks'), - url(r'^attachment/(?P\d+)/(?P[^/]+)/$', - views.attachment, name='contact_attachment'), + url(r'^attachment/(?P\d+)/(?P[^/]+)/$', views.attachment, name='contact_attachment'), ) diff --git a/contact/utils.py b/contact/utils.py index ce37833..bba8c34 100644 --- a/contact/utils.py +++ b/contact/utils.py @@ -1,8 +1,12 @@ +# -*- coding: utf-8 -*- + + def csv_escape(string): return '"' + string.replace('\r\n', ' ').replace('\n', ' ').replace('"', '\"') + '"' + def csv_prepare(obj): to_escape = obj if not isinstance(obj, unicode): to_escape = str(to_escape) - return csv_escape(to_escape) \ No newline at end of file + return csv_escape(to_escape) diff --git a/contact/views.py b/contact/views.py index 20d28a3..823c046 100644 --- a/contact/views.py +++ b/contact/views.py @@ -1,7 +1,7 @@ +# -*- coding: utf-8 -*- from django.contrib.auth.decorators import permission_required -from django.http import Http404, HttpResponse +from django.http import Http404 from django.shortcuts import get_object_or_404, redirect, render -from django.utils.translation import ugettext_lazy as _ from fnpdjango.utils.views import serve_file from .forms import contact_forms from .models import Attachment @@ -35,10 +35,10 @@ def form(request, form_tag, force_enabled=False): formsets = [] for formset in getattr(form, 'form_formsets', ()): formsets.append(formset()) - return render(request, - ['contact/%s/form.html' % form_tag, 'contact/form.html'], - {'form': form, 'formsets': formsets} - ) + return render( + request, ['contact/%s/form.html' % form_tag, 'contact/form.html'], + {'form': form, 'formsets': formsets} + ) def thanks(request, form_tag): @@ -47,10 +47,9 @@ def thanks(request, form_tag): except KeyError: raise Http404 - return render(request, - ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'], - dict(base_template = getattr(form_class, 'base_template', None)) - ) + return render( + request, ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'], + {'base_template': getattr(form_class, 'base_template', None)}) @permission_required('contact.change_attachment') diff --git a/curriculum/admin.py b/curriculum/admin.py index 4e83537..0f378bc 100755 --- a/curriculum/admin.py +++ b/curriculum/admin.py @@ -1,19 +1,23 @@ +# -*- coding: utf-8 -*- from django.contrib import admin -from .models import (Competence, CompetenceLevel, Level, Section, - CurriculumCourse, CurriculumLevel, Curriculum) +from .models import Competence, CompetenceLevel, Level, Section, CurriculumCourse, CurriculumLevel, Curriculum + class CompetenceLevelInline(admin.TabularInline): model = CompetenceLevel + class CompetenceAdmin(admin.ModelAdmin): model = Competence list_display = ['name_pl', 'name_en', 'section', 'slug', 'order'] inlines = [CompetenceLevelInline] + class LevelAdmin(admin.ModelAdmin): model = Level list_display = ['name_pl', 'name_en', 'group_pl', 'group_en', 'slug', 'order'] + class SectionAdmin(admin.ModelAdmin): model = Section list_display = ['name_pl', 'name_en', 'slug', 'order'] diff --git a/curriculum/models.py b/curriculum/models.py index a5d531f..22de956 100644 --- a/curriculum/models.py +++ b/curriculum/models.py @@ -28,7 +28,7 @@ class Section(models.Model): return "%s?s=%d&level=%s&d=1" % (reverse("curriculum"), self.pk, level.slug) add_translatable(Section, { - 'name': models.CharField(_('name'), max_length=255, default = '') + 'name': models.CharField(_('name'), max_length=255, default='') }) @@ -65,7 +65,7 @@ class Competence(models.Model): return cls.objects.get(**{lookup_field_name: parts[1].strip()}) add_translatable(Competence, { - 'name': models.CharField(_('name'), max_length=255, default = '') + 'name': models.CharField(_('name'), max_length=255, default='') }) @@ -73,9 +73,11 @@ class Level(models.Model): slug = models.CharField(_('slug'), max_length=255, unique=True) meta_name = models.CharField(_('meta name'), max_length=255, unique=True) order = models.IntegerField(_('order')) - package = models.FileField(upload_to=lambda i, f: "curriculum/pack/edukacjamedialna_%s.zip" % i.slug, + package = models.FileField( + upload_to=lambda i, f: "curriculum/pack/edukacjamedialna_%s.zip" % i.slug, null=True, blank=True, max_length=255, storage=bofh_storage) - student_package = models.FileField(upload_to=lambda i, f: "curriculum/pack/edukacjamedialna_%s_uczen.zip" % i.slug, + student_package = models.FileField( + upload_to=lambda i, f: "curriculum/pack/edukacjamedialna_%s_uczen.zip" % i.slug, null=True, blank=True, max_length=255, storage=bofh_storage) class Meta: @@ -127,10 +129,9 @@ class Level(models.Model): self.build_package(True) - add_translatable(Level, { - 'name': models.CharField(_('name'), max_length=255, default = ''), - 'group': models.CharField(_('group'), max_length=255, default = '') + 'name': models.CharField(_('name'), max_length=255, default=''), + 'group': models.CharField(_('group'), max_length=255, default='') }) @@ -150,7 +151,7 @@ class CompetenceLevel(models.Model): return "%s?c=%d&level=%s&d=1" % (reverse("curriculum"), self.competence.pk, self.level.slug) add_translatable(CompetenceLevel, { - 'description': models.TextField(_('description'), default = '') + 'description': models.TextField(_('description'), default='') }) @@ -199,8 +200,7 @@ class Curriculum(models.Model): @classmethod def from_text(cls, identifier, title): m = re.match(r"^\d+/(?P[^/]+)/(?P[^/]+)/" - "(?P(?:%s))[^/]+(?P/roz)?" % - "|".join(cls.TYPES), identifier) + r"(?P(?:%s))[^/]+(?P/roz)?" % "|".join(cls.TYPES), identifier) assert m is not None, "Curriculum identifier doesn't match template." level, created = CurriculumLevel.objects.get_or_create( title=m.group('level')) @@ -225,4 +225,3 @@ class Curriculum(models.Model): curr.type = type_ curr.save() return curr - diff --git a/curriculum/templatetags/curriculum_tags.py b/curriculum/templatetags/curriculum_tags.py index 7757150..cc37d0e 100755 --- a/curriculum/templatetags/curriculum_tags.py +++ b/curriculum/templatetags/curriculum_tags.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django import template from django.utils.datastructures import SortedDict from ..models import Competence, Curriculum, CurriculumCourse @@ -11,17 +12,19 @@ def competence(texts, level): try: comps = [Competence.from_text(text) for text in texts] except: + # WTF return {'texts': texts} return { 'comps': comps, 'level': level, } + @register.inclusion_tag("curriculum/snippets/curriculum.html") def curriculum(identifiers): try: currs = [Curriculum.objects.get(identifier__iexact=identifier.replace(' ', '')) - for identifier in identifiers] + for identifier in identifiers] except Curriculum.DoesNotExist: return {'identifiers': identifiers} @@ -45,6 +48,7 @@ def url_for_level(comp, level): try: return comp.url_for_level(level) except: + # WTF return comp.get_absolute_url() @@ -65,16 +69,20 @@ def course_box(course): "lessons": lessons, } + @register.inclusion_tag("curriculum/snippets/course_boxes.html") def course_boxes(): return {'object_list': CurriculumCourse.objects.all()} + @register.inclusion_tag("curriculum/snippets/course_boxes_toc.html") def course_boxes_toc(accusative=False): last = None, None object_list = [] - for l in Lesson.curriculum_courses.through.objects.all().select_related('lesson__level', 'curriculumcourse').order_by( - 'lesson__level', 'curriculumcourse'): + lessons = Lesson.curriculum_courses.through.objects\ + .select_related('lesson__level', 'curriculumcourse')\ + .order_by('lesson__level', 'curriculumcourse') + for l in lessons: level, course = l.lesson.level, l.curriculumcourse if (level, course) == last: continue diff --git a/curriculum/tests.py b/curriculum/tests.py index 501deb7..b967c44 100644 --- a/curriculum/tests.py +++ b/curriculum/tests.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- """ This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". diff --git a/curriculum/urls.py b/curriculum/urls.py index 0fa940a..7553a66 100755 --- a/curriculum/urls.py +++ b/curriculum/urls.py @@ -1,7 +1,9 @@ -from django.conf.urls import patterns, include, url +# -*- coding: utf-8 -*- +from django.conf.urls import patterns, url from .views import CompetenceDetailView, CompetencesView -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^$', CompetencesView.as_view(), name='curriculum'), url(r'^(?P[^/]+)/$', CompetenceDetailView.as_view(), name='curriculum_competence'), ) diff --git a/edumed/contact_forms.py b/edumed/contact_forms.py index 3e7abab..b7972c7 100644 --- a/edumed/contact_forms.py +++ b/edumed/contact_forms.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from django import forms +from django.forms.formsets import BaseFormSet from contact.forms import ContactForm from django.core.mail import send_mail from django.core.exceptions import ValidationError @@ -26,15 +27,16 @@ class CooperateForm(ContactForm): podpis = forms.CharField(label=u'Imię i nazwisko', max_length=128) contact = forms.EmailField(label=u'E-mail', max_length=128) - instytucja = forms.CharField(label=u'Instytucja (nazwa, adres)', - widget=forms.Textarea, max_length=1000, required=False) + instytucja = forms.CharField( + label=u'Instytucja (nazwa, adres)', widget=forms.Textarea, max_length=1000, required=False) uwagi = forms.CharField(label=u'Uwagi', widget=forms.Textarea, max_length=1800, required=False) zajecia_przedszkole = forms.BooleanField(label=u'Prowadzę zajęcia z dziećmi w wieku przedszkolnym', required=False) zajecia_sp13 = forms.BooleanField(label=u'Prowadzę zajęcia z dziećmi z SP kl. 1-3', required=False) zajecia_sp46 = forms.BooleanField(label=u'Prowadzę zajęcia z dziećmi z SP kl. 4-6', required=False) zajecia_gimnazjum = forms.BooleanField(label=u'Prowadzę zajęcia z młodzieżą w wieku gimnazjalnym', required=False) - zajecia_ponadgimnazjalne = forms.BooleanField(label=u'Prowadzę zajęcia z młodzieżą ze szkół ponadgimnazjalnych', required=False) + zajecia_ponadgimnazjalne = forms.BooleanField( + label=u'Prowadzę zajęcia z młodzieżą ze szkół ponadgimnazjalnych', required=False) zajecia_wyzsze = forms.BooleanField(label=u'Prowadzę zajęcia w szkole wyższej', required=False) zajecia_dorosli = forms.BooleanField(label=u'Prowadzę zajęcia dla dorosłych', required=False) zajecia_seniorzy = forms.BooleanField(label=u'Prowadzę zajęcia dla seniorów', required=False) @@ -47,28 +49,29 @@ class ContestForm(ContactForm): nazwisko = forms.CharField(label=u'Imię i nazwisko', max_length=128) contact = forms.EmailField(label=u'Adres e-mail', max_length=128) - instytucja = forms.CharField(label=u'Instytucja (nazwa, adres)', - widget=forms.Textarea, max_length=1000) - tytul = forms.CharField(label=u'Tytuł przeprowadzonej lekcji', - help_text=u'proszę wymienić wszystkie, jeśli zostały przeprowadzone więcej niż jedne zajęcia', - widget=forms.Textarea, max_length=1000) + instytucja = forms.CharField(label=u'Instytucja (nazwa, adres)', widget=forms.Textarea, max_length=1000) + tytul = forms.CharField( + label=u'Tytuł przeprowadzonej lekcji', + help_text=u'proszę wymienić wszystkie, jeśli zostały przeprowadzone więcej niż jedne zajęcia', + widget=forms.Textarea, max_length=1000) uczestnicy = forms.CharField(label=u'Liczba uczestników', max_length=64) - trudnosci = forms.CharField(label=u'Czy w trakcie zajęć pojawiły się jakieś trudności? Jeśli tak, to jakie?', - widget=forms.Textarea, max_length=2000) - pomocne = forms.CharField(label=u'Co w materiałach okazało się najbardziej pomocne w przygotowaniu i prowadzeniu lekcji?', - widget=forms.Textarea, max_length=2000) - nieprzydatne = forms.CharField(label=u'Co w materiałach okazało się nieprzydatne w przygotowaniu i prowadzeniu lekcji?', - widget=forms.Textarea, max_length=2000) - poprawic = forms.CharField(label=u'Jak możemy poprawić serwis edukacjamedialna.edu.pl?', - widget=forms.Textarea, max_length=2000, - required=False) - inne = forms.CharField(label=u'Inne uwagi i komentarze', - widget=forms.Textarea, max_length=2000, - required=False) + trudnosci = forms.CharField( + label=u'Czy w trakcie zajęć pojawiły się jakieś trudności? Jeśli tak, to jakie?', + widget=forms.Textarea, max_length=2000) + pomocne = forms.CharField( + label=u'Co w materiałach okazało się najbardziej pomocne w przygotowaniu i prowadzeniu lekcji?', + widget=forms.Textarea, max_length=2000) + nieprzydatne = forms.CharField( + label=u'Co w materiałach okazało się nieprzydatne w przygotowaniu i prowadzeniu lekcji?', + widget=forms.Textarea, max_length=2000) + poprawic = forms.CharField( + label=u'Jak możemy poprawić serwis edukacjamedialna.edu.pl?', + widget=forms.Textarea, max_length=2000, required=False) + inne = forms.CharField(label=u'Inne uwagi i komentarze', widget=forms.Textarea, max_length=2000, required=False) zgoda_regulamin = forms.BooleanField( label=u'Znam i akceptuję regulamin konkursu Medialog.', - help_text=u'Zobacz regulamin konkursu MediaLog.' - ) + help_text=u'Zobacz ' + u'regulamin konkursu MediaLog.') zgoda_informacje = forms.BooleanField( label=u'Wyrażam zgodę na otrzymywanie informacji od Fundacji Nowoczesna Polska związanych z edukacją medialną.', required=False @@ -94,8 +97,9 @@ class WTEMStudentForm(forms.Form): email = forms.EmailField(label=u'Adres e-mail', max_length=128) form_tag = "student" + # FIXME: doesn't do what is says anymore. -class NoEmptyFormsAllowedBaseFormSet(forms.formsets.BaseFormSet): +class NoEmptyFormsAllowedBaseFormSet(BaseFormSet): """ Won't allow formset_factory to be submitted with no forms """ @@ -104,10 +108,11 @@ class NoEmptyFormsAllowedBaseFormSet(forms.formsets.BaseFormSet): for form in self.forms: if form.cleaned_data: needed -= 1 - #return + # return if needed > 0: raise forms.ValidationError(u"Proszę podać dane przynajmniej trzech osób.") + class WTEMForm(ContactForm): disabled = True disabled_template = 'wtem/disabled_contact_form.html' @@ -115,7 +120,8 @@ class WTEMForm(ContactForm): form_title = u"WTEM - rejestracja uczestników" submit_label = u"Wyślij zgłoszenie" admin_list = ['imie', 'nazwisko', 'institution'] - form_formsets = (forms.formsets.formset_factory(WTEMStudentForm, formset=NoEmptyFormsAllowedBaseFormSet, max_num=5, validate_max=True, extra=5),) + form_formsets = (forms.formsets.formset_factory( + WTEMStudentForm, formset=NoEmptyFormsAllowedBaseFormSet, max_num=5, validate_max=True, extra=5),) contact = forms.EmailField(label=u'Adres e-mail opiekuna/opiekunki', max_length=128) imie = forms.CharField(label=u'Imię', max_length=128) @@ -129,18 +135,22 @@ class WTEMForm(ContactForm): zgoda_regulamin = forms.BooleanField( label=u'Znam i akceptuję regulamin Wielkiego Turnieju Edukacji Medialnej.', - help_text=u'Zobacz regulamin Wielkiego Turnieju Edukacji Medialnej.' + help_text=u'Zobacz ' + u'regulamin Wielkiego Turnieju Edukacji Medialnej.' ) zgoda_dane = forms.BooleanField( label=u'Wyrażam zgodę na przetwarzanie moich danych osobowych oraz danych osobowych moich podopiecznych.', - #help_text=u'Zobacz pełną treść oświadczenia.' + # help_text=u'Zobacz ' + # 'pełną treść oświadczenia.' ) potw_uczniowie = forms.BooleanField( - label=u'Potwierdzam, że zgłoszeni Uczestnicy/Uczestniczki w chwili rejestracji są uczniami/uczennicami szkoły ponadgimnazjalnej.', + label=u'Potwierdzam, że zgłoszeni Uczestnicy/Uczestniczki w chwili rejestracji są ' + u'uczniami/uczennicami szkoły ponadgimnazjalnej.', ) zgoda_informacje = forms.BooleanField( - label=u'Wyrażam zgodę na otrzymywanie informacji od Fundacji Nowoczesna Polska związanych z edukacją medialną.', + label=u'Wyrażam zgodę na otrzymywanie informacji od Fundacji Nowoczesna Polska ' + u'związanych z edukacją medialną.', required=False ) @@ -169,7 +179,7 @@ class WTEMForm(ContactForm): for student in contact.body['student']: for attr in ('first_name', 'last_name', 'email'): current['student_' + attr] = student[attr] - if not current in toret: + if current not in toret: toret.append(current) current = dict() return toret @@ -187,7 +197,8 @@ class WTEMForm(ContactForm): except ValidationError: pass else: - send_mail(mail_subject, mail_body, 'edukacjamedialna@nowoczesnapolska.org.pl', [email], fail_silently=True) + send_mail(mail_subject, mail_body, 'edukacjamedialna@nowoczesnapolska.org.pl', [email], + fail_silently=True) return contact @@ -199,38 +210,34 @@ class MILForm(ContactForm): base_template = 'base_mil.html' site_name = site_domain = 'katalog.nowoczesnapolska.org.pl' - name = forms.CharField(label = _('Name and Surname'), max_length = 255) - contact = forms.EmailField(label = _('E-mail'), max_length = 255) + name = forms.CharField(label=_('Name and Surname'), max_length=255) + contact = forms.EmailField(label=_('E-mail'), max_length=255) - institution = forms.CharField(label =_('Institution'), widget = forms.Textarea, max_length = 8192) + institution = forms.CharField(label=_('Institution'), widget=forms.Textarea, max_length=8192) question_stages = forms.CharField( - label = _('What do you think about the proposed educational stages classification?'), - widget = forms.Textarea, - max_length = 255, - required = False - ) + label=_('What do you think about the proposed educational stages classification?'), + widget=forms.Textarea, + max_length=255, + required=False) question_fields = forms.CharField( - label = _('What do you think about the proposed thematic fields?'), - widget = forms.Textarea, - max_length = 255, - required = False - ) + label=_('What do you think about the proposed thematic fields?'), + widget=forms.Textarea, + max_length=255, + required=False) question_left_out = forms.CharField( - label = _('What important areas of media and information literacy have been left out?'), - widget = forms.Textarea, - max_length = 255, - required = False - ) + label=_('What important areas of media and information literacy have been left out?'), + widget=forms.Textarea, + max_length=255, + required=False) other = forms.CharField( - label = _('Other suggestions and comments'), - widget = forms.Textarea, - max_length = 255, - required = False - ) + label=_('Other suggestions and comments'), + widget=forms.Textarea, + max_length=255, + required=False) class TEMForm(ContactForm): @@ -243,18 +250,24 @@ class TEMForm(ContactForm): contact = forms.EmailField(label=u'E-mail', max_length=128) telefon = forms.CharField(label=u'Tel. kontaktowy', max_length=128) instytucja = forms.CharField(label=u'Instytucja', max_length=256) - adres = forms.CharField(label=u'Adres', - widget=forms.Textarea, max_length=1000) + adres = forms.CharField(label=u'Adres', widget=forms.Textarea, max_length=1000) stanowisko = forms.CharField(label=u'Stanowisko', max_length=256) - doswiadczenie = forms.CharField(label=u'Jakie jest Pani/Pana doświadczenie w zakresie edukacji medialnej?', - widget=forms.Textarea, max_length=500, help_text=u'(max 500 znaków)') - dlaczego = forms.CharField(label=u'Dlaczego chce Pani/Pan wziąć udział w szkoleniu?', - widget=forms.Textarea, max_length=500, help_text=u'(max 500 znaków)') - jak_wykorzystac = forms.CharField(label=u'Jak zamierza Pan/Pani wykorzystać wiedzę zdobytą w czasie szkolenia?', - widget=forms.Textarea, max_length=500, help_text=u'(max 500 znaków)') - - zajecia = forms.BooleanField(label=u'W okresie wrzesień-październik 2015 r. przeprowadzę min. 2 godziny zajęć edukacji medialnej z wybraną grupą dzieci lub młodzieży.', required=True) - zgoda_informacje = forms.BooleanField(label=u'Wyrażam zgodę na otrzymywanie informacji od Fundacji Nowoczesna Polska związanych z edukacją medialną.', required=False) + doswiadczenie = forms.CharField( + label=u'Jakie jest Pani/Pana doświadczenie w zakresie edukacji medialnej?', + widget=forms.Textarea, max_length=500, help_text=u'(max 500 znaków)') + dlaczego = forms.CharField( + label=u'Dlaczego chce Pani/Pan wziąć udział w szkoleniu?', + widget=forms.Textarea, max_length=500, help_text=u'(max 500 znaków)') + jak_wykorzystac = forms.CharField( + label=u'Jak zamierza Pan/Pani wykorzystać wiedzę zdobytą w czasie szkolenia?', + widget=forms.Textarea, max_length=500, help_text=u'(max 500 znaków)') + + zajecia = forms.BooleanField( + label=u'W okresie wrzesień-październik 2015 r. przeprowadzę min. 2 godziny zajęć edukacji medialnej ' + u'z wybraną grupą dzieci lub młodzieży.', required=True) + zgoda_informacje = forms.BooleanField( + label=u'Wyrażam zgodę na otrzymywanie informacji od Fundacji Nowoczesna Polska ' + u'związanych z edukacją medialną.', required=False) class SuperwizjaForm(ContactForm): @@ -270,28 +283,62 @@ class SuperwizjaForm(ContactForm): termin = forms.CharField(label=u'Termin zajęć', max_length=1024) czas_trwania = forms.CharField(label=u'Czas trwania zajęć', max_length=1024) miejsce = forms.CharField(label=u'Miejsce prowadzenia zajęć', max_length=1024) - rodzaj = forms.ChoiceField(label=u'Rodzaj zajęć', widget=forms.RadioSelect, choices=[('jednorazowe', 'jednorazowe'), ('w ramach cyklu', 'w ramach cyklu')]) + rodzaj = forms.ChoiceField( + label=u'Rodzaj zajęć', widget=forms.RadioSelect, + choices=[('jednorazowe', 'jednorazowe'), ('w ramach cyklu', 'w ramach cyklu')]) cykl = forms.CharField(label=u'Jeśli w ramach cyklu, to podaj jego temat i czas trwania', required=False) - sposob = forms.ChoiceField(label=u'Sposób prowadzenia zajęć', widget=forms.RadioSelect, choices=[('samodzielnie', 'samodzielnie'), (u'z drugą osobą', 'z drugą osobą')]) - wrazenia = forms.CharField(label=u'Opisz Twoje ogólne wrażenia po warsztacie.', widget=forms.Textarea, max_length=4096) - opiekun = forms.CharField(label=u'Czy opiekun grupy był obecny podczas zajęć? Jeśli tak, opisz krótko jego rolę.', widget=forms.Textarea, max_length=4096) - grupa = forms.CharField(label=u'Opisz krótko grupę uczestników zajęć (wiek, liczba osób, czy to pierwszy kontakt z grupą).', widget=forms.Textarea, max_length=4096) - cel = forms.CharField(label=u'Jaki był założony cel zajęć? Dlaczego wybrałaś/eś taki cel?', widget=forms.Textarea, max_length=4096) - ewaluacja = forms.CharField(label=u'W jaki sposób sprawdziłeś/aś, czy cel zajęć został zrealizowany? Opisz krótko efekty zajęć.', widget=forms.Textarea, max_length=4096) + sposob = forms.ChoiceField( + label=u'Sposób prowadzenia zajęć', widget=forms.RadioSelect, + choices=[('samodzielnie', 'samodzielnie'), (u'z drugą osobą', 'z drugą osobą')]) + wrazenia = forms.CharField( + label=u'Opisz Twoje ogólne wrażenia po warsztacie.', widget=forms.Textarea, max_length=4096) + opiekun = forms.CharField( + label=u'Czy opiekun grupy był obecny podczas zajęć? Jeśli tak, opisz krótko jego rolę.', + widget=forms.Textarea, max_length=4096) + grupa = forms.CharField( + label=u'Opisz krótko grupę uczestników zajęć (wiek, liczba osób, czy to pierwszy kontakt z grupą).', + widget=forms.Textarea, max_length=4096) + cel = forms.CharField( + label=u'Jaki był założony cel zajęć? Dlaczego wybrałaś/eś taki cel?', widget=forms.Textarea, max_length=4096) + ewaluacja = forms.CharField( + label=u'W jaki sposób sprawdziłeś/aś, czy cel zajęć został zrealizowany? Opisz krótko efekty zajęć.', + widget=forms.Textarea, max_length=4096) # header - przygotowania = forms.CharField(label=u'Opisz w punktach proces przygotowania się do zajęć.', widget=forms.Textarea, max_length=4096) - przygotowania_trudnosci = forms.CharField(label=u'Co na etapie przygotowań sprawiło Ci największą trudność?', widget=forms.Textarea, max_length=4096) - przygotowania_pomoc = forms.CharField(label=u'Co było pomocne w przygotowaniu zajęć? (Czy korzystałaś/eś z materiałów z serwisu edukacjamedialna.edu.pl? Jeśli tak, to jakich?)', widget=forms.Textarea, max_length=4096) - narzedzia = forms.CharField(label=u'Jakie narzędzie/a planowałaś/eś wykorzystać, a jakie wykorzystałaś/eś?', widget=forms.Textarea, max_length=4096) - struktura = forms.CharField(label=u'Opisz w punktach strukturę zajęć. Zaznacz ile czasu planowałaś/eś na każdą część, a ile czasu faktycznie Ci to zajęło.', widget=forms.Textarea, max_length=4096) - prowadzenie_trudnosci = forms.CharField(label=u'Co sprawiało Ci trudność w prowadzeniu zajęć?', widget=forms.Textarea, max_length=4096) - prowadzenie_pomoc = forms.CharField(label=u'Co było pomocne w prowadzeniu zajęć?', widget=forms.Textarea, max_length=4096) - kontrakt = forms.CharField(label=u'W jakiej formie został zawarty kontrakt z uczestnikami? Jakie zasady zostały przyjęte? Czy w trakcie zajęć Ty bądź uczestnicy odwoływaliście się do kontraktu?', widget=forms.Textarea, max_length=4096) - trudne_sytuacje = forms.CharField(label=u'Czy podczas zajęć miały miejsce tzw. „trudne sytuacje”. Jak na nie zareagowałaś/eś? Czy potrzebowałabyś/łbyś czegoś w związku z nimi?', widget=forms.Textarea, max_length=4096) - informacje_zwrotne = forms.CharField(label=u'Czy zbierałaś/eś informacje zwrotne od uczestników? Jeśli tak, na co zwrócili uwagę? W jaki sposób zbierałaś/eś informacje zwrotne?', widget=forms.Textarea, max_length=4096) - - mocne_strony = forms.CharField(label=u'Opisz w punktach mocne strony przeprowadzonych zajęć.', widget=forms.Textarea, max_length=4096) - zmiany = forms.CharField(label=u'Opisz w punktach, co byś zmienił(a) na przyszłość.', widget=forms.Textarea, max_length=4096) - potrzeby = forms.CharField(label=u'Czy potrzebowałbyś/łbyś czegoś przed następnymi zajęciami?', widget=forms.Textarea, max_length=4096) + przygotowania = forms.CharField( + label=u'Opisz w punktach proces przygotowania się do zajęć.', widget=forms.Textarea, max_length=4096) + przygotowania_trudnosci = forms.CharField( + label=u'Co na etapie przygotowań sprawiło Ci największą trudność?', widget=forms.Textarea, max_length=4096) + przygotowania_pomoc = forms.CharField( + label=u'Co było pomocne w przygotowaniu zajęć? ' + u'(Czy korzystałaś/eś z materiałów z serwisu edukacjamedialna.edu.pl? Jeśli tak, to jakich?)', + widget=forms.Textarea, max_length=4096) + narzedzia = forms.CharField( + label=u'Jakie narzędzie/a planowałaś/eś wykorzystać, a jakie wykorzystałaś/eś?', + widget=forms.Textarea, max_length=4096) + struktura = forms.CharField( + label=u'Opisz w punktach strukturę zajęć. ' + u'Zaznacz ile czasu planowałaś/eś na każdą część, a ile czasu faktycznie Ci to zajęło.', + widget=forms.Textarea, max_length=4096) + prowadzenie_trudnosci = forms.CharField( + label=u'Co sprawiało Ci trudność w prowadzeniu zajęć?', widget=forms.Textarea, max_length=4096) + prowadzenie_pomoc = forms.CharField( + label=u'Co było pomocne w prowadzeniu zajęć?', widget=forms.Textarea, max_length=4096) + kontrakt = forms.CharField( + label=u'W jakiej formie został zawarty kontrakt z uczestnikami? Jakie zasady zostały przyjęte? ' + u'Czy w trakcie zajęć Ty bądź uczestnicy odwoływaliście się do kontraktu?', + widget=forms.Textarea, max_length=4096) + trudne_sytuacje = forms.CharField( + label=u'Czy podczas zajęć miały miejsce tzw. „trudne sytuacje”. ' + u'Jak na nie zareagowałaś/eś? Czy potrzebowałabyś/łbyś czegoś w związku z nimi?', + widget=forms.Textarea, max_length=4096) + informacje_zwrotne = forms.CharField( + label=u'Czy zbierałaś/eś informacje zwrotne od uczestników? Jeśli tak, na co zwrócili uwagę? ' + u'W jaki sposób zbierałaś/eś informacje zwrotne?', widget=forms.Textarea, max_length=4096) + + mocne_strony = forms.CharField( + label=u'Opisz w punktach mocne strony przeprowadzonych zajęć.', widget=forms.Textarea, max_length=4096) + zmiany = forms.CharField( + label=u'Opisz w punktach, co byś zmienił(a) na przyszłość.', widget=forms.Textarea, max_length=4096) + potrzeby = forms.CharField( + label=u'Czy potrzebowałbyś/łbyś czegoś przed następnymi zajęciami?', widget=forms.Textarea, max_length=4096) uwagi = forms.CharField(label=u'Inne uwagi', widget=forms.Textarea, max_length=4096, required=False) - diff --git a/edumed/context_processors.py b/edumed/context_processors.py index 63e1df1..ed57c24 100644 --- a/edumed/context_processors.py +++ b/edumed/context_processors.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- def base_template(request): base_template = 'base_mil.html' if request.META.get('HTTP_HOST').startswith('katalog') else 'base.html' - return dict(base_template = base_template) \ No newline at end of file + return dict(base_template = base_template) diff --git a/edumed/forms.py b/edumed/forms.py index 554779f..650197b 100644 --- a/edumed/forms.py +++ b/edumed/forms.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from pybb.forms import EditProfileForm @@ -8,10 +9,9 @@ class AvatarlessEditProfileForm(EditProfileForm): signature = forms.CharField( widget=forms.Textarea(attrs={'rows': 2, 'cols:': 60}), required=False, - label = _('Signature') + label=_('Signature') ) class Meta: model = util.get_pybb_profile_model() - fields = ['signature', 'time_zone', 'language', - 'show_signatures'] + fields = ['signature', 'time_zone', 'language', 'show_signatures'] diff --git a/edumed/forum.py b/edumed/forum.py index 4b194a8..86cfb0c 100644 --- a/edumed/forum.py +++ b/edumed/forum.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from pybb.permissions import DefaultPermissionHandler @@ -22,4 +23,3 @@ class ForumPermissionHandler(DefaultPermissionHandler): return False return user.is_authenticated() - \ No newline at end of file diff --git a/edumed/milurls.py b/edumed/milurls.py index b68f1ba..dea2558 100644 --- a/edumed/milurls.py +++ b/edumed/milurls.py @@ -1,10 +1,13 @@ +# -*- coding: utf-8 -*- from django.conf.urls import include, url, patterns +from django.conf import settings from fnpdjango.utils.urls import i18n_patterns from .views import mil_home_view, mil_contact_view, mil_knowledge_base_view -urlpatterns = i18n_patterns('', +urlpatterns = i18n_patterns( + '', url(r'^$', mil_home_view, name="mil_home"), url(r'^kompetencje/', include('curriculum.urls')), url(r'^wez-udzial/', include('comment.urls')), @@ -16,10 +19,10 @@ urlpatterns = i18n_patterns('', handler404 = 'edumed.views.mil_404_view' -from django.conf import settings if settings.DEBUG: - urlpatterns += patterns('', + urlpatterns += patterns( + '', url(r'^media/(?P.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), - ) + ) diff --git a/edumed/settings.py b/edumed/settings.py index e9b77f0..c5df1a7 100644 --- a/edumed/settings.py +++ b/edumed/settings.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- import os.path import glob diff --git a/edumed/urls.py b/edumed/urls.py index e7cd5f0..43ed0a8 100644 --- a/edumed/urls.py +++ b/edumed/urls.py @@ -4,7 +4,8 @@ from django.conf import settings from .views import HomeView, AvatarlessProfileEditView -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^$', HomeView.as_view(), name="home"), url(r'^lekcje/', include('catalogue.urls')), url(r'^info/(?P.*)$', 'django.contrib.flatpages.views.flatpage', @@ -25,17 +26,20 @@ if 'django.contrib.admin' in settings.INSTALLED_APPS: admin.autodiscover() if 'django_cas' in settings.INSTALLED_APPS: - urlpatterns += patterns('', + urlpatterns += patterns( + '', (r'^admin/logout/$', 'django_cas.views.logout'), ) - urlpatterns += patterns('', + urlpatterns += patterns( + '', url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), ) # Auth stuff, if necessary if 'django_cas' in settings.INSTALLED_APPS: - urlpatterns += patterns('', + urlpatterns += patterns( + '', url(r'^accounts/login/$', 'django_cas.views.login', name='login'), url(r'^accounts/logout/$', 'django_cas.views.logout', name='logout'), ) @@ -54,8 +58,9 @@ if settings.DEBUG: if settings.DEBUG: - urlpatterns += patterns('', + urlpatterns += patterns( + '', url(r'^media/(?P.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), - ) + ) diff --git a/edumed/views.py b/edumed/views.py index 712570d..47c5d16 100644 --- a/edumed/views.py +++ b/edumed/views.py @@ -1,26 +1,31 @@ -import os.path -from django.conf import settings -from django.views.generic import TemplateView -from django.views.defaults import page_not_found +# -*- coding: utf-8 -*- from django.contrib.flatpages.views import flatpage +from django.views.defaults import page_not_found +from django.views.generic import TemplateView from pybb.views import ProfileEditView + from .forms import AvatarlessEditProfileForm class HomeView(TemplateView): - template_name="home.html" + template_name = "home.html" + def mil_home_view(request): - return flatpage(request, url = '/' if request.LANGUAGE_CODE == 'pl' else '/en/') + return flatpage(request, url='/' if request.LANGUAGE_CODE == 'pl' else '/en/') + def mil_404_view(request): return page_not_found(request, '404_mil.html') + def mil_contact_view(request): - return flatpage(request, url = '/kontakt_mil/' if request.LANGUAGE_CODE == 'pl' else '/contact_mil/') + return flatpage(request, url='/kontakt_mil/' if request.LANGUAGE_CODE == 'pl' else '/contact_mil/') + def mil_knowledge_base_view(request, url): - return flatpage(request, url = 'bazawiedzy/' + url) + return flatpage(request, url='bazawiedzy/' + url) + class AvatarlessProfileEditView(ProfileEditView): form_class = AvatarlessEditProfileForm diff --git a/fabfile.py b/fabfile.py index b157b2c..5e108a7 100644 --- a/fabfile.py +++ b/fabfile.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from fnpdjango.deploy import * env.project_name = 'edumed' diff --git a/forum/forms.py b/forum/forms.py index 9e931db..37c9b35 100644 --- a/forum/forms.py +++ b/forum/forms.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django import forms from django.forms.models import ModelChoiceIterator from django.utils.translation import ugettext as _ @@ -15,7 +16,7 @@ class GroupedModelChoiceIterator(ModelChoiceIterator): def choice(self, obj): items_query = self.items_queryset.filter(**{self.field.grouping_fk_field: obj}) items = [super(GroupedModelChoiceIterator, self).choice(item) for item in items_query.all()] - return (unicode(obj), items) + return unicode(obj), items class GroupedModelChoiceField(forms.ModelChoiceField): @@ -35,5 +36,6 @@ class GroupedModelChoiceField(forms.ModelChoiceField): class PostForm(pybb.forms.PostForm): - lesson = GroupedModelChoiceField(label = _('Related lesson'), queryset = Lesson.objects.all(), - grouping_fk_field = 'section', required = False) + lesson = GroupedModelChoiceField( + label=_('Related lesson'), queryset=Lesson.objects.all(), + grouping_fk_field='section', required=False) diff --git a/forum/middleware.py b/forum/middleware.py index fb0a605..1b6e26b 100644 --- a/forum/middleware.py +++ b/forum/middleware.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from urllib import urlencode from django.contrib.auth import REDIRECT_FIELD_NAME @@ -6,9 +7,10 @@ from django.core.urlresolvers import reverse from django_cas.views import login as cas_login -class ForumMiddleware: - def process_request(self, request): +class ForumMiddleware(object): + @staticmethod + def process_request(request): if request.path.startswith(reverse('pybb:index')) \ - and (not hasattr(request, 'user') or not request.user.is_authenticated()): + and (not hasattr(request, 'user') or not request.user.is_authenticated()): params = urlencode({REDIRECT_FIELD_NAME: request.get_full_path()}) return HttpResponseRedirect(reverse(cas_login) + '?' + params) diff --git a/forum/models.py b/forum/models.py index 7a9c359..5ec506b 100644 --- a/forum/models.py +++ b/forum/models.py @@ -1,5 +1,5 @@ +# -*- coding: utf-8 -*- from django.db import models -from django.db.models.signals import post_save import pybb.models @@ -7,6 +7,5 @@ from catalogue.models import Lesson class Topic(models.Model): - pybb_topic = models.OneToOneField(pybb.models.Topic, primary_key = True, related_name = 'edumed_topic') - lesson = models.ForeignKey(Lesson, null = True, blank = True, related_name = 'forum_topics') - \ No newline at end of file + pybb_topic = models.OneToOneField(pybb.models.Topic, primary_key=True, related_name='edumed_topic') + lesson = models.ForeignKey(Lesson, null=True, blank=True, related_name='forum_topics') diff --git a/forum/search_indexes.py b/forum/search_indexes.py index 5add363..0a3f413 100644 --- a/forum/search_indexes.py +++ b/forum/search_indexes.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from haystack import indexes from pybb.models import Post diff --git a/forum/urls.py b/forum/urls.py index 309e9a7..c669808 100644 --- a/forum/urls.py +++ b/forum/urls.py @@ -1,4 +1,5 @@ -from django.conf.urls import patterns, include, url +# -*- coding: utf-8 -*- +from django.conf.urls import patterns, url from haystack.query import SearchQuerySet from haystack.views import SearchView, search_view_factory from haystack.forms import SearchForm @@ -7,17 +8,19 @@ from pybb.models import Post from .views import AddPostView, EditPostView -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^forum/(?P\d+)/topic/add/$', AddPostView.as_view()), url(r'^post/(?P\d+)/edit/$', EditPostView.as_view()), ) PostsSearchQuerySet = SearchQuerySet().models(Post).highlight() -urlpatterns += patterns('haystack.views', +urlpatterns += patterns( + 'haystack.views', url(r'^szukaj/$', search_view_factory( - view_class = SearchView, - template = 'forum/search_results.html', - searchqueryset = PostsSearchQuerySet, - form_class = SearchForm - ), name='forum_search')) \ No newline at end of file + view_class=SearchView, + template='forum/search_results.html', + searchqueryset=PostsSearchQuerySet, + form_class=SearchForm + ), name='forum_search')) diff --git a/forum/views.py b/forum/views.py index 41b7eb8..6750d99 100644 --- a/forum/views.py +++ b/forum/views.py @@ -1,9 +1,8 @@ +# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist import pybb.views import pybb.forms -from catalogue.models import Lesson - from .forms import PostForm from .models import Topic @@ -21,7 +20,7 @@ class PostEditMixin(pybb.views.PostEditMixin): pybb_post = self.object pybb_topic = pybb_post.topic - topic, topic_created = Topic.objects.get_or_create(pybb_topic = pybb_topic) + topic, topic_created = Topic.objects.get_or_create(pybb_topic=pybb_topic) if pybb_post == pybb_topic.head: topic.lesson = form.cleaned_data['lesson'] diff --git a/lib/librarian b/lib/librarian index 0c0cedf..63cfa40 160000 --- a/lib/librarian +++ b/lib/librarian @@ -1 +1 @@ -Subproject commit 0c0cedf9c06fb93e1ba187efcf48d81c028f37a4 +Subproject commit 63cfa40372a9d33c84c0e4b61ed505173c780eae diff --git a/publishers/admin.py b/publishers/admin.py index 5e2cf36..95bd7ab 100644 --- a/publishers/admin.py +++ b/publishers/admin.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django.contrib import admin from .models import Publisher diff --git a/publishers/models.py b/publishers/models.py index 10d1947..14ed63a 100644 --- a/publishers/models.py +++ b/publishers/models.py @@ -1,5 +1,7 @@ +# -*- coding: utf-8 -*- from django.db import models + class Publisher(models.Model): name = models.CharField(max_length=255) logo = models.ImageField(upload_to='publishers/logo') diff --git a/wtem/admin.py b/wtem/admin.py index 78ca9b9..56a687d 100644 --- a/wtem/admin.py +++ b/wtem/admin.py @@ -1,24 +1,22 @@ # -*- coding: utf-8 -*- +import json -import os - -from django.contrib import admin from django import forms -from django.utils import simplejson -from django.utils.safestring import mark_safe -from django.core.urlresolvers import reverse from django.conf.urls import url, patterns -from django.shortcuts import render +from django.contrib import admin from django.contrib.auth.models import User +from django.core.urlresolvers import reverse from django.http import HttpResponse from django.template.loader import render_to_string -from .models import Submission, Assignment, Attachment, exercises +from django.utils.safestring import mark_safe + from .middleware import get_current_request +from .models import Submission, Assignment, Attachment, exercises def get_user_exercises(user): try: - assignment = Assignment.objects.get(user = user) + assignment = Assignment.objects.get(user=user) return [e for e in exercises if e['id'] in assignment.exercises] except Assignment.DoesNotExist: return [] @@ -26,6 +24,7 @@ def get_user_exercises(user): readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent') + class AttachmentWidget(forms.Widget): def render(self, name, value, *args, **kwargs): if value: @@ -34,6 +33,7 @@ class AttachmentWidget(forms.Widget): a_tag = 'brak' return mark_safe(('' % (name, value)) + a_tag) + class TextareaWithLinks(forms.Textarea): def render(self, name, value, *args, **kwargs): t, links = value @@ -45,6 +45,7 @@ class TextareaWithLinks(forms.Textarea): output += mark_safe(moreoutput + "") return output + class SubmissionFormBase(forms.ModelForm): class Meta: model = Submission @@ -68,7 +69,7 @@ def get_open_answer(answers, exercise): else: toret = answer if exercise['type'] == 'edumed_wybor': - ok = set(map(str, exercise['answer'])) == set(map(str,answer['closed_part'])) + ok = set(map(str, exercise['answer'])) == set(map(str, answer['closed_part'])) toret = u'Czesc testowa [%s]:\n' % ('poprawna' if ok else 'niepoprawna') if len(answer['closed_part']): for selected in answer['closed_part']: @@ -84,8 +85,8 @@ def get_open_answer(answers, exercise): def get_form(request, submission): fields = dict() - if submission.answers: - answers = simplejson.loads(submission.answers) + if submission and submission.answers: + answers = json.loads(submission.answers) user_exercises = get_user_exercises(request.user) for exercise in exercises: if exercise not in user_exercises: @@ -96,14 +97,14 @@ def get_form(request, submission): if exercise['type'] in ('open', 'file_upload') or exercise.get('open_part', None): if exercise['type'] == 'file_upload': try: - attachment = Attachment.objects.get(submission = submission, exercise_id = exercise['id']) + attachment = Attachment.objects.get(submission=submission, exercise_id=exercise['id']) except Attachment.DoesNotExist: attachment = None widget = AttachmentWidget initial = attachment.file.url if attachment else None else: - #widget = forms.Textarea(attrs={'readonly':True}) - widget = TextareaWithLinks(attrs={'readonly':True}) + # widget = forms.Textarea(attrs={'readonly':True}) + widget = TextareaWithLinks(attrs={'readonly': True}) links = [] qfiles = [] for qfield in exercise.get('fields', []): @@ -121,21 +122,21 @@ def get_form(request, submission): initial = get_open_answer(answers, exercise), links fields[answer_field_name] = forms.CharField( - widget = widget, - initial = initial, - label = u'Rozwiązanie zadania %s' % exercise['id'], - required = False + widget=widget, + initial=initial, + label=u'Rozwiązanie zadania %s' % exercise['id'], + required=False ) - choices = [(None, '-')] # + [(i,i) for i in range(exercise['max_points']+1)], + choices = [(None, '-')] # + [(i,i) for i in range(exercise['max_points']+1)], i = 0 while i <= exercise['max_points']: choices.append((i, i)) i += .5 fields[mark_field_name] = forms.ChoiceField( - choices = choices, - initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']), - label = u'Twoja ocena zadania %s' % exercise['id'] + choices=choices, + initial=submission.get_mark(user_id=request.user.id, exercise_id=exercise['id']), + label=u'Twoja ocena zadania %s' % exercise['id'] ) if not request.user.is_superuser: @@ -151,27 +152,30 @@ class SubmissionAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'todo', 'examiners_repr') readonly_fields = readonly_fields - def get_form(self, request, obj, **kwargs): + def get_form(self, request, obj=None, **kwargs): return get_form(request, obj) - - def submitted_by(self, instance): + + @staticmethod + def submitted_by(instance): if instance.contact: return '%s' % ( - reverse('admin:contact_contact_change', args = [instance.contact.id]), + reverse('admin:contact_contact_change', args=[instance.contact.id]), instance.contact.contact ) return '-' submitted_by.allow_tags = True submitted_by.short_description = "Zgłoszony/a przez" - def todo(self, submission): + @staticmethod + def todo(submission): user = get_current_request().user user_exercises = get_user_exercises(user) user_marks = submission.marks.get(str(user.id), {}) return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()]) todo.short_description = 'Twoje nieocenione zadania' - def examiners_repr(self, submission): + @staticmethod + def examiners_repr(submission): return ', '.join([u.username for u in submission.examiners.all()]) examiners_repr.short_description = 'Przypisani do zgłoszenia' @@ -181,32 +185,33 @@ class SubmissionAdmin(admin.ModelAdmin): parts = name.split('_') exercise_id = parts[1] user_id = parts[3] - submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value) + submission.set_mark(user_id=user_id, exercise_id=exercise_id, mark=value) submission.save() def changelist_view(self, request, extra_context=None): - context = dict(examiners = []) + context = dict(examiners=[]) assignments = Assignment.objects.all() if not request.user.is_superuser: - assignments = assignments.filter(user = request.user) + assignments = assignments.filter(user=request.user) for assignment in assignments: - examiner = dict(name = assignment.user.username, todo = 0) - for submission in Submission.objects.filter(examiners = assignment.user): + examiner = dict(name=assignment.user.username, todo=0) + for submission in Submission.objects.filter(examiners=assignment.user): for exercise_id in assignment.exercises: - if submission.get_mark(user_id = assignment.user.id, exercise_id = exercise_id) is None: + if submission.get_mark(user_id=assignment.user.id, exercise_id=exercise_id) is None: examiner['todo'] += 1 context['examiners'].append(examiner) - return super(SubmissionAdmin, self).changelist_view(request, extra_context = context) + return super(SubmissionAdmin, self).changelist_view(request, extra_context=context) def queryset(self, request): qs = super(SubmissionAdmin, self).queryset(request) if not request.user.is_superuser: - qs = qs.filter(examiners = request.user) + qs = qs.filter(examiners=request.user) return qs def get_urls(self): urls = super(SubmissionAdmin, self).get_urls() - return patterns('', + return patterns( + '', url(r'^report/$', self.admin_site.admin_view(report_view), name='wtem_admin_report') ) + super(SubmissionAdmin, self).get_urls() @@ -214,23 +219,22 @@ class SubmissionAdmin(admin.ModelAdmin): class SubmissionsSet: def __init__(self, submissions): self.submissions = submissions - self.examiners_by_exercise = dict() + self.examiners_by_exercise = {} for submission in submissions: for user_id, marks in submission.marks.items(): user = User.objects.get(pk=user_id) for exercise_id in marks.keys(): examiners = self.examiners_by_exercise.setdefault(exercise_id, []) - if not user in examiners: + if user not in examiners: examiners.append(user) + def report_view(request): - submissions = sorted(Submission.objects.all(), key = lambda s: -s.final_result) - toret = render_to_string('wtem/admin_report.csv', dict( - submissionsSet = SubmissionsSet(submissions), - #exercise_ids = map(str, range(1,len(exercises)+1)) - exercise_ids = [str(e['id']) for e in exercises] - )) - response = HttpResponse(toret, content_type = 'text/csv') + submissions = sorted(Submission.objects.all(), key=lambda s: -s.final_result) + toret = render_to_string('wtem/admin_report.csv', { + 'submissionsSet': SubmissionsSet(submissions), + 'exercise_ids': [str(e['id']) for e in exercises]}) + response = HttpResponse(toret, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="wyniki.csv"' return response diff --git a/wtem/forms.py b/wtem/forms.py index 504fd26..ae406a3 100644 --- a/wtem/forms.py +++ b/wtem/forms.py @@ -1,8 +1,7 @@ -import os +# -*- coding: utf-8 -*- import re from django import forms -from django.utils import simplejson from .models import Submission, Attachment, exercises @@ -17,18 +16,17 @@ class WTEMForm(forms.ModelForm): for exercise in exercises: if exercise['type'] != 'file_upload': continue - self.fields['attachment_for_' + str(exercise['id'])] = forms.FileField(required = False) + self.fields['attachment_for_' + str(exercise['id'])] = forms.FileField(required=False) def save(self, commit=True): submission = super(WTEMForm, self).save(commit=commit) - for name, file in self.files.items(): + for name, attachment_file in self.files.items(): m = re.match(r'attachment_for_(\d+)(?:__(.*))?', name) exercise_id = int(m.group(1)) tag = m.group(2) or None try: - attachment = Attachment.objects.get(submission = submission, exercise_id = exercise_id, tag=tag) + attachment = Attachment.objects.get(submission=submission, exercise_id=exercise_id, tag=tag) except Attachment.DoesNotExist: - attachment = Attachment(submission = submission, exercise_id = exercise_id, tag=tag) - attachment.file = file + attachment = Attachment(submission=submission, exercise_id=exercise_id, tag=tag) + attachment.file = attachment_file attachment.save() - diff --git a/wtem/management/commands/wtem_assign_submissions.py b/wtem/management/commands/wtem_assign_submissions.py index 7ff1af2..dcf0466 100644 --- a/wtem/management/commands/wtem_assign_submissions.py +++ b/wtem/management/commands/wtem_assign_submissions.py @@ -1,22 +1,24 @@ +# -*- coding: utf-8 -*- from optparse import make_option -from django.core.management.base import BaseCommand, CommandError +from django.core.management.base import BaseCommand from django.db.models import Count from django.contrib.auth.models import User -from contact.models import Contact from wtem.models import Submission, Attachment class Command(BaseCommand): option_list = BaseCommand.option_list + ( - make_option('--with-attachments-only', + make_option( + '--with-attachments-only', action='store_true', dest='attachments_only', default=False, help='Take into account only submissions with attachments'), - make_option('--without-attachments-only', + make_option( + '--without-attachments-only', action='store_true', dest='no_attachments_only', default=False, @@ -29,16 +31,16 @@ class Command(BaseCommand): limit_to = int(args[1]) examiner_names = args[2:] - users = User.objects.filter(username__in = examiner_names) - submissions_query = Submission.objects.annotate(examiners_count = Count('examiners')) + users = User.objects.filter(username__in=examiner_names) + all_submissions = Submission.objects.annotate(examiners_count=Count('examiners')) + + submissions = all_submissions.exclude(answers=None) - submissions = submissions_query.exclude(answers = None) - with_attachment_ids = Attachment.objects.values_list('submission_id', flat=True).all() if options['attachments_only']: - submissions = submissions.filter(id__in = with_attachment_ids) + submissions = submissions.filter(id__in=with_attachment_ids) if options['no_attachments_only']: - submissions = submissions.exclude(id__in = with_attachment_ids) + submissions = submissions.exclude(id__in=with_attachment_ids) for submission in submissions.order_by('id')[limit_from:limit_to]: submission.examiners.add(*users) @@ -46,7 +48,7 @@ class Command(BaseCommand): self.stdout.write('added to %s:%s' % (submission.id, submission.email)) count_by_examiners = dict() - for submission in submissions_query.all(): + for submission in all_submissions.all(): count_by_examiners[submission.examiners_count] = \ count_by_examiners.get(submission.examiners_count, 0) + 1 self.stdout.write('%s' % count_by_examiners) diff --git a/wtem/management/commands/wtem_email_teachers.py b/wtem/management/commands/wtem_email_teachers.py index e0986f8..9b5e5e9 100644 --- a/wtem/management/commands/wtem_email_teachers.py +++ b/wtem/management/commands/wtem_email_teachers.py @@ -1,14 +1,10 @@ # -*- coding: utf-8 -*- -import sys -from optparse import make_option - -from django.core.management.base import BaseCommand, CommandError -from django.conf import settings -from wtem.management.commands import send_mail +from django.core.management.base import BaseCommand from django.template.loader import render_to_string from contact.models import Contact +from wtem.management.commands import send_mail class Command(BaseCommand): @@ -16,12 +12,13 @@ class Command(BaseCommand): sent = 0 failed = 0 - query = Contact.objects.filter(form_tag = 'wtem').order_by('contact').distinct('contact') + query = Contact.objects.filter(form_tag='wtem').order_by('contact').distinct('contact') template_name = args[0] message = render_to_string('wtem/' + template_name + '.txt') subject = render_to_string('wtem/' + template_name + '_subject.txt') - answer = raw_input('Send the following to %d teachers with subject "%s"\n\n %s\n\n?' % \ + answer = raw_input( + 'Send the following to %d teachers with subject "%s"\n\n %s\n\n?' % (query.count(), subject.encode('utf8'), message.encode('utf8'))) if answer == 'yes': @@ -39,9 +36,5 @@ class Command(BaseCommand): def send_message(self, message, subject, email): self.stdout.write('>>> sending to %s' % email) - send_mail( - subject = subject, - body = message, - to = [email] - ) + send_mail(subject=subject, body=message, to=[email]) diff --git a/wtem/management/commands/wtem_send_results.py b/wtem/management/commands/wtem_send_results.py index c443ed1..fdc539c 100644 --- a/wtem/management/commands/wtem_send_results.py +++ b/wtem/management/commands/wtem_send_results.py @@ -3,7 +3,6 @@ from optparse import make_option from django.core.management.base import BaseCommand -from django.conf import settings from wtem.management.commands import send_mail from django.utils import translation from django.template.loader import render_to_string @@ -13,24 +12,28 @@ from wtem.models import Submission def get_submissions(): - return sorted(Submission.objects.exclude(answers = None).all(), key=lambda s: -s.final_result) + return sorted(Submission.objects.exclude(answers=None).all(), key=lambda s: -s.final_result) minimum = 55 + class Command(BaseCommand): option_list = BaseCommand.option_list + ( - make_option('--to-teachers', + make_option( + '--to-teachers', action='store_true', dest='to_teachers', default=False, help='Send emails to teachers'), - make_option('--to-students', + make_option( + '--to-students', action='store_true', dest='to_students', default=False, help='Send emails to students'), - make_option('--only-to', + make_option( + '--only-to', action='store', dest='only_to', default=None, @@ -57,7 +60,7 @@ class Command(BaseCommand): template = 'results_student_failed.txt' else: template = 'results_student_passed.txt' - message = render_to_string('wtem/' + template, dict(final_result = submission.final_result)) + message = render_to_string('wtem/' + template, dict(final_result=submission.final_result)) self.send_message(message, subject, submission.email) self.sum_up() @@ -76,7 +79,7 @@ class Command(BaseCommand): for contact_id, submissions in submissions_by_contact.items(): contact = Contact.objects.get(id=contact_id) - message = render_to_string('wtem/results_teacher.txt', dict(submissions = submissions)) + message = render_to_string('wtem/results_teacher.txt', dict(submissions=submissions)) self.send_message(message, subject, contact.contact) self.sum_up() @@ -87,16 +90,10 @@ class Command(BaseCommand): def send_message(self, message, subject, email): self.stdout.write('>>> sending results to %s' % email) try: - send_mail( - subject = subject, - body = message, - to = [email] - ) + send_mail(subject=subject, body=message, to=[email]) except BaseException, e: self.failed += 1 self.stdout.write('failed sending to: ' + email + ': ' + str(e)) else: self.sent += 1 self.stdout.write('message sent to: ' + email) - - diff --git a/wtem/management/commands/wtem_send_results_csv.py b/wtem/management/commands/wtem_send_results_csv.py index 0d15c17..a9d6e9a 100644 --- a/wtem/management/commands/wtem_send_results_csv.py +++ b/wtem/management/commands/wtem_send_results_csv.py @@ -3,35 +3,37 @@ from optparse import make_option from django.core.management.base import BaseCommand -from django.conf import settings -from wtem.management.commands import send_mail -from django.utils import translation from django.template.loader import render_to_string +from django.utils import translation -from contact.models import Contact +from wtem.management.commands import send_mail from wtem.models import Submission def get_submissions(): - return sorted(Submission.objects.exclude(answers = None).all(), key=lambda s: -s.final_result) + return sorted(Submission.objects.exclude(answers=None).all(), key=lambda s: -s.final_result) minimum = 55 + class Command(BaseCommand): args = 'csv_filename' option_list = BaseCommand.option_list + ( - make_option('--to-teachers', + make_option( + '--to-teachers', action='store_true', dest='to_teachers', default=False, help='Send emails to teachers'), - make_option('--to-students', + make_option( + '--to-students', action='store_true', dest='to_students', default=False, help='Send emails to students'), - make_option('--only-to', + make_option( + '--only-to', action='store', dest='only_to', default=None, @@ -67,11 +69,11 @@ class Command(BaseCommand): def handle_to_teachers(self, *args, **options): self.stdout.write('>>> Sending results to teachers') subject = 'Wyniki I etapu Wielkiego Turnieju Edukacji Medialnej' - failed = sent = 0 submissions_by_contact = dict() from decimal import Decimal, InvalidOperation + def dec_or_0(s): try: return Decimal(s) @@ -89,7 +91,7 @@ class Command(BaseCommand): for email, submissions in submissions_by_contact.items(): # contact = Contact.objects.get(id=contact_id) - message = render_to_string('wtem/results_teacher.txt', dict(submissions = submissions)) + message = render_to_string('wtem/results_teacher.txt', dict(submissions=submissions)) self.send_message(message, subject, email) self.sum_up() @@ -100,16 +102,10 @@ class Command(BaseCommand): def send_message(self, message, subject, email): self.stdout.write('>>> sending results to %s' % email) try: - send_mail( - subject = subject, - body = message, - to = [email] - ) + send_mail(subject=subject, body=message, to=[email]) except BaseException, e: self.failed += 1 self.stdout.write('failed sending to: ' + email + ': ' + str(e)) else: self.sent += 1 self.stdout.write('message sent to: ' + email) - - diff --git a/wtem/middleware.py b/wtem/middleware.py index d9bd308..eb26e41 100644 --- a/wtem/middleware.py +++ b/wtem/middleware.py @@ -1,15 +1,15 @@ -try: - from threading import local -except ImportError: - from django.utils._threading_local import local +# -*- coding: utf-8 -*- +from threading import local _thread_locals = local() + def get_current_request(): return getattr(_thread_locals, 'request', None) -class ThreadLocalMiddleware: - def process_request(self, request): - _thread_locals.request = request \ No newline at end of file +class ThreadLocalMiddleware(object): + @staticmethod + def process_request(request): + _thread_locals.request = request diff --git a/wtem/templatetags/wtem_csv.py b/wtem/templatetags/wtem_csv.py index 2c96704..028836c 100644 --- a/wtem/templatetags/wtem_csv.py +++ b/wtem/templatetags/wtem_csv.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- from django import template register = template.Library() @@ -12,6 +13,7 @@ def csv_header(exercise_id, submissionSet): toret += ',' + examiners_string return toret + @register.simple_tag def csv_row_fragment(exercise_id, submission, submissionSet): final_mark = submission.get_final_exercise_mark(exercise_id) diff --git a/wtem/urls.py b/wtem/urls.py index 51a7618..3e96c2e 100644 --- a/wtem/urls.py +++ b/wtem/urls.py @@ -2,7 +2,8 @@ from django.conf.urls import patterns, url from .views import form, form_during -urlpatterns = patterns('', +urlpatterns = patterns( + '', url(r'^_test/(?P.*)/$', form_during), url(r'^(?P.*)/$', form, name='wtem_form') )