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
13 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
14 exercises = simplejson.loads(f.read())
17 def get_user_exercises(user):
18 assignment = Assignment.objects.get(user = user)
19 return [e for e in exercises if e['id'] in assignment.exercises]
22 readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent')
25 class SubmissionFormBase(forms.ModelForm):
28 exclude = ('answers', 'marks', 'contact') + readonly_fields
31 def get_form(request, submission):
33 if submission.answers:
34 answers = simplejson.loads(submission.answers)
35 user_exercises = get_user_exercises(request.user)
36 for exercise in exercises:
37 if exercise not in user_exercises:
39 if exercise['type'] == 'open':
40 answer_field_name = 'exercise_%s' % exercise['id']
41 mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
42 fields[answer_field_name] = forms.CharField(
43 widget = forms.Textarea(attrs={'readonly':True}),
44 initial = answers[str(exercise['id'])],
45 label = 'Rozwiązanie zadania %s' % exercise['id']
48 fields[mark_field_name] = forms.ChoiceField(
49 choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
50 initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
51 label = u'Twoja ocena zadania %s' % exercise['id']
53 return type('SubmissionForm', (SubmissionFormBase,), fields)
56 class SubmissionAdmin(admin.ModelAdmin):
57 readonly_fields = readonly_fields
59 def get_form(self, request, obj, **kwargs):
60 return get_form(request, obj)
62 def submitted_by(self, instance):
64 return '<a href="%s">%s</a>' % (
65 reverse('admin:contact_contact_change', args = [instance.contact.id]),
66 instance.contact.contact
69 submitted_by.allow_tags = True
70 submitted_by.short_description = "Zgłoszony/a przez"
72 def save_model(self, request, submission, form, change):
73 for name, value in form.cleaned_data.items():
74 if name.startswith('markof_'):
75 parts = name.split('_')
76 exercise_id = parts[1]
78 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
82 admin.site.register(Submission, SubmissionAdmin)
83 admin.site.register(Assignment)