+# -*- 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']
admin.site.register(Section)
admin.site.register(Lesson, LessonAdmin)
admin.site.register(LessonStub)
-
#
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 ...]'
read_dir(path)
return files
-
+ @transaction.atomic
def handle(self, *directories, **options):
- from django.db import connection, transaction
levels = set()
self.style = color_style()
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
# 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.
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:
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()
# 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
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)
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:
@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):
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:
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
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
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
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,
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,
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):
# -*- 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
# 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
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):
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:
-import datetime
+# -*- coding: utf-8 -*-
from haystack import indexes
from .models import Lesson
+# -*- coding: utf-8 -*-
from collections import defaultdict
from django import template
from django.utils.datastructures import SortedDict
"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 [
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)
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':
'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,
"added": added,
}
+
@register.inclusion_tag("catalogue/snippets/lesson_nav.html")
def lesson_nav(lesson):
if lesson.type == 'course':
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:
"siblings": siblings,
}
+
@register.inclusion_tag("catalogue/snippets/lesson_link.html")
def lesson_link(uri):
try:
except Lesson.DoesNotExist:
return {}
+
@register.filter
def person_list(persons):
return u", ".join(Person.from_text(p).readable() for p in 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:
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,
+# -*- coding: utf-8 -*-
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
-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"),
-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):
try:
context['publisher'] = Publisher.objects.get(
name=context['object'].dc.get('publisher', '').strip())
- except:
+ except (Publisher.DoesNotExist, Publisher.MultipleObjectsReturned):
pass
return context
+# -*- coding: utf-8 -*-
from django.contrib import admin
from chunks.models import Chunk, Attachment
list_display = ('key',)
search_fields = ('key',)
-admin.site.register(Attachment, AttachmentAdmin)
\ No newline at end of file
+admin.site.register(Attachment, AttachmentAdmin)
+# -*- coding: utf-8 -*-
from django.core.cache import cache
from django.db import models
from django.utils.translation import ugettext_lazy as _
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)
def __unicode__(self):
return self.key
-
+# -*- coding: utf-8 -*-
from django import template
-from django.db import models
from django.core.cache import cache
from ..models import Chunk, Attachment
return c.attachment.url
except Attachment.DoesNotExist:
return ''
-
-
+# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import CommentDocument
+# -*- 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']
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})
-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<slug>[^/]+)/$', CommentDocument.as_view(), name = 'comment_document')
-)
\ No newline at end of file
+urlpatterns = patterns(
+ '',
+ url('^$', CommentDocumentList.as_view(), name='comment_document_index'),
+ url('^(?P<slug>[^/]+)/$', CommentDocument.as_view(), name='comment_document')
+)
+# -*- 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)
+# -*- coding: utf-8 -*-
"""
Generic app for creating contact forms.
+# -*- 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
def __getattr__(cls, name):
if name.startswith('admin_list_'):
return lambda self: ""
- raise AttributeError, name
+ raise AttributeError(name)
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)
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)
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<form_tag>[\w-]+)/(?P<extract_type_slug>[\w-]+)/$', self.admin_site.admin_view(extract_view), name='contact_extract')
+ # urls = super(ContactAdmin, self).get_urls()
+ return patterns(
+ '',
+ url(r'^extract/(?P<form_tag>[\w-]+)/(?P<extract_type_slug>[\w-]+)/$',
+ self.admin_site.admin_view(extract_view), name='contact_extract')
) + super(ContactAdmin, self).get_urls()
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():
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)
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
+# -*- coding: utf-8 -*-
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import UploadedFile
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))
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)
'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)
'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
# -*- 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 _
@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
@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)
+# -*- 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)
+# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from . import views
-urlpatterns = patterns('contact.views',
+urlpatterns = patterns(
+ 'contact.views',
url(r'^(?P<form_tag>[^/]+)/$', views.form, name='contact_form'),
url(r'^(?P<form_tag>[^/]+)/thanks/$', views.thanks, name='contact_thanks'),
- url(r'^attachment/(?P<contact_id>\d+)/(?P<tag>[^/]+)/$',
- views.attachment, name='contact_attachment'),
+ url(r'^attachment/(?P<contact_id>\d+)/(?P<tag>[^/]+)/$', views.attachment, name='contact_attachment'),
)
+# -*- 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)
+# -*- 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
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):
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')
+# -*- 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']
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='')
})
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='')
})
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:
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='')
})
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='')
})
@classmethod
def from_text(cls, identifier, title):
m = re.match(r"^\d+/(?P<level>[^/]+)/(?P<course>[^/]+)/"
- "(?P<type>(?:%s))[^/]+(?P<roz>/roz)?" %
- "|".join(cls.TYPES), identifier)
+ r"(?P<type>(?:%s))[^/]+(?P<roz>/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'))
curr.type = type_
curr.save()
return curr
-
+# -*- coding: utf-8 -*-
from django import template
from django.utils.datastructures import SortedDict
from ..models import Competence, Curriculum, CurriculumCourse
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}
try:
return comp.url_for_level(level)
except:
+ # WTF
return comp.get_absolute_url()
"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
+# -*- coding: utf-8 -*-
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
-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<slug>[^/]+)/$', CompetenceDetailView.as_view(), name='curriculum_competence'),
)
# -*- 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
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)
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 <a href="/media/chunks/attachment/Regulamin_konkursu_MediaLog_1.pdf">regulamin konkursu MediaLog</a>.'
- )
+ help_text=u'Zobacz <a href="/media/chunks/attachment/Regulamin_konkursu_MediaLog_1.pdf">'
+ u'regulamin konkursu MediaLog</a>.')
zgoda_informacje = forms.BooleanField(
label=u'Wyrażam zgodę na otrzymywanie informacji od Fundacji Nowoczesna Polska związanych z edukacją medialną.',
required=False
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
"""
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'
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)
zgoda_regulamin = forms.BooleanField(
label=u'Znam i akceptuję regulamin Wielkiego Turnieju Edukacji Medialnej.',
- help_text=u'Zobacz <a href="/media/chunks/attachment/regulamin_III_edycja.pdf">regulamin Wielkiego Turnieju Edukacji Medialnej</a>.'
+ help_text=u'Zobacz <a href="/media/chunks/attachment/regulamin_III_edycja.pdf">'
+ u'regulamin Wielkiego Turnieju Edukacji Medialnej</a>.'
)
zgoda_dane = forms.BooleanField(
label=u'Wyrażam zgodę na przetwarzanie moich danych osobowych oraz danych osobowych moich podopiecznych.',
- #help_text=u'Zobacz <a href="/media/chunks/attachment/Oswiadczenie_o_danych_osobowych.pdf">pełną treść oświadczenia</a>.'
+ # help_text=u'Zobacz <a href="/media/chunks/attachment/Oswiadczenie_o_danych_osobowych.pdf">'
+ # 'pełną treść oświadczenia</a>.'
)
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
)
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
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
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):
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):
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)
-
+# -*- 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)
+# -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from pybb.forms import 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']
+# -*- coding: utf-8 -*-
from pybb.permissions import DefaultPermissionHandler
return False
return user.is_authenticated()
-
\ No newline at end of file
+# -*- 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')),
handler404 = 'edumed.views.mil_404_view'
-from django.conf import settings
if settings.DEBUG:
- urlpatterns += patterns('',
+ urlpatterns += patterns(
+ '',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
- )
+ )
+# -*- coding: utf-8 -*-
import os.path
import glob
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<url>.*)$', 'django.contrib.flatpages.views.flatpage',
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'),
)
if settings.DEBUG:
- urlpatterns += patterns('',
+ urlpatterns += patterns(
+ '',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
- )
+ )
-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
+# -*- coding: utf-8 -*-
from fnpdjango.deploy import *
env.project_name = 'edumed'
+# -*- coding: utf-8 -*-
from django import forms
from django.forms.models import ModelChoiceIterator
from django.utils.translation import ugettext as _
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):
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)
+# -*- coding: utf-8 -*-
from urllib import urlencode
from django.contrib.auth import REDIRECT_FIELD_NAME
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)
+# -*- coding: utf-8 -*-
from django.db import models
-from django.db.models.signals import post_save
import pybb.models
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')
+# -*- coding: utf-8 -*-
from haystack import indexes
from pybb.models import Post
-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
from .views import AddPostView, EditPostView
-urlpatterns = patterns('',
+urlpatterns = patterns(
+ '',
url(r'^forum/(?P<forum_id>\d+)/topic/add/$', AddPostView.as_view()),
url(r'^post/(?P<pk>\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'))
+# -*- 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
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']
-Subproject commit 0c0cedf9c06fb93e1ba187efcf48d81c028f37a4
+Subproject commit 63cfa40372a9d33c84c0e4b61ed505173c780eae
+# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Publisher
+# -*- 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')
# -*- 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 []
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:
a_tag = 'brak'
return mark_safe(('<input type="hidden" name="%s" value="%s"/>' % (name, value)) + a_tag)
+
class TextareaWithLinks(forms.Textarea):
def render(self, name, value, *args, **kwargs):
t, links = value
output += mark_safe(moreoutput + "</div>")
return output
+
class SubmissionFormBase(forms.ModelForm):
class Meta:
model = Submission
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']:
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:
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', []):
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:
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 '<a href="%s">%s</a>' % (
- 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'
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()
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
-import os
+# -*- coding: utf-8 -*-
import re
from django import forms
-from django.utils import simplejson
from .models import Submission, Attachment, exercises
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()
-
+# -*- 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,
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)
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)
# -*- 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):
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':
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])
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
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,
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()
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()
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)
-
-
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,
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)
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()
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)
-
-
-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
+# -*- coding: utf-8 -*-
from django import template
register = template.Library()
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)
from django.conf.urls import patterns, url
from .views import form, form_during
-urlpatterns = patterns('',
+urlpatterns = patterns(
+ '',
url(r'^_test/(?P<key>.*)/$', form_during),
url(r'^(?P<key>.*)/$', form, name='wtem_form')
)