1 # -*- coding: utf-8 -*-
5 from django.contrib import admin
6 from django import forms
7 from django.utils import simplejson
8 from django.core.urlresolvers import reverse
10 from .models import Submission, Assignment
11 from .middleware import get_current_request
14 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
15 exercises = simplejson.loads(f.read())
18 def get_user_exercises(user):
19 assignment = Assignment.objects.get(user = user)
20 return [e for e in exercises if e['id'] in assignment.exercises]
23 readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent')
26 class SubmissionFormBase(forms.ModelForm):
29 exclude = ('answers', 'marks', 'contact') + readonly_fields
32 def get_form(request, submission):
34 if submission.answers:
35 answers = simplejson.loads(submission.answers)
36 user_exercises = get_user_exercises(request.user)
37 for exercise in exercises:
38 if exercise not in user_exercises:
40 if exercise['type'] == 'open':
41 answer_field_name = 'exercise_%s' % exercise['id']
42 mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
43 fields[answer_field_name] = forms.CharField(
44 widget = forms.Textarea(attrs={'readonly':True}),
45 initial = answers[str(exercise['id'])],
46 label = 'Rozwiązanie zadania %s' % exercise['id']
49 fields[mark_field_name] = forms.ChoiceField(
50 choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
51 initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
52 label = u'Twoja ocena zadania %s' % exercise['id']
54 return type('SubmissionForm', (SubmissionFormBase,), fields)
57 class SubmissionAdmin(admin.ModelAdmin):
58 list_display = ('__unicode__', 'todo',)
59 readonly_fields = readonly_fields
61 def get_form(self, request, obj, **kwargs):
62 return get_form(request, obj)
64 def submitted_by(self, instance):
66 return '<a href="%s">%s</a>' % (
67 reverse('admin:contact_contact_change', args = [instance.contact.id]),
68 instance.contact.contact
71 submitted_by.allow_tags = True
72 submitted_by.short_description = "Zgłoszony/a przez"
74 def todo(self, submission):
75 user = get_current_request().user
76 user_exercises = get_user_exercises(user)
77 user_marks = submission.marks.get(str(user.id), {})
78 return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
80 def save_model(self, request, submission, form, change):
81 for name, value in form.cleaned_data.items():
82 if name.startswith('markof_'):
83 parts = name.split('_')
84 exercise_id = parts[1]
86 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
90 admin.site.register(Submission, SubmissionAdmin)
91 admin.site.register(Assignment)