1 # -*- coding: utf-8 -*-
5 from django.contrib import admin
6 from django import forms
7 from django.utils import simplejson
9 from .models import Submission, Assignment
12 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
13 exercises = simplejson.loads(f.read())
16 def get_user_exercises(user):
17 assignment = Assignment.objects.get(user = user)
18 return [e for e in exercises if e['id'] in assignment.exercises]
21 readonly_fields = ('contact', 'first_name', 'last_name', 'email', 'key', 'key_sent')
24 class SubmissionFormBase(forms.ModelForm):
27 exclude = ('answers', 'marks') + readonly_fields
30 def get_form(request, submission):
32 if submission.answers:
33 answers = simplejson.loads(submission.answers)
34 user_exercises = get_user_exercises(request.user)
35 for exercise in exercises:
36 if exercise not in user_exercises:
38 if exercise['type'] == 'open':
39 answer_field_name = 'exercise_%s' % exercise['id']
40 mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
41 fields[answer_field_name] = forms.CharField(
42 widget = forms.Textarea(attrs={'readonly':True}),
43 initial = answers[str(exercise['id'])],
44 label = 'Rozwiązanie zadania %s' % exercise['id']
47 fields[mark_field_name] = forms.ChoiceField(
48 choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
49 initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
50 label = u'Twoja ocena zadania %s' % exercise['id']
52 return type('SubmissionForm', (SubmissionFormBase,), fields)
55 class SubmissionAdmin(admin.ModelAdmin):
56 readonly_fields = readonly_fields
58 def get_form(self, request, obj, **kwargs):
59 return get_form(request, obj)
61 def save_model(self, request, submission, form, change):
62 for name, value in form.cleaned_data.items():
63 if name.startswith('markof_'):
64 parts = name.split('_')
65 exercise_id = parts[1]
67 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
71 admin.site.register(Submission, SubmissionAdmin)
72 admin.site.register(Assignment)