This commit is contained in:
Ross
2021-02-26 15:19:23 +00:00
parent 1456090d1c
commit 2e89b6e7ec
10 changed files with 140 additions and 29 deletions
+35
View File
@@ -70,6 +70,8 @@ class RapidCreationDefaultForm(ModelForm):
class RapidForm(ModelForm):
exams = ModelMultipleChoiceField(required=False, queryset=Exam.objects.all())
class Media:
# Django also includes a few javascript files necessary
# for the operation of this form element. You need to
@@ -106,6 +108,39 @@ class RapidForm(ModelForm):
choices=Rapid.LATERALITY_CHOICES, required=True, widget=RadioSelect()
)
if kwargs.get("instance"):
# We get the 'initial' keyword argument or initialize it
# as a dict if it didn't exist.
initial = kwargs.setdefault("initial", {})
# The widget for a ModelMultipleChoiceField expects
# a list of primary key for the selected data.
initial["exams"] = [t.pk for t in kwargs["instance"].exams.all()]
ModelForm.__init__(self, *args, **kwargs)
def save(self, commit=True):
# Get the unsaved Pizza instance
instance = ModelForm.save(self, False)
# Prepare a 'save_m2m' method for the form,
old_save_m2m = self.save_m2m
def save_m2m():
old_save_m2m()
# This is where we actually link the pizza with toppings
instance.exams.clear()
for exam in self.cleaned_data["exams"]:
instance.exams.add(exam)
self.save_m2m = save_m2m
# Do we need to save all changes now?
# if commit:
instance.save()
self.save_m2m()
return instance
class Meta:
model = Rapid
# fields = ['due_back']
+11
View File
@@ -0,0 +1,11 @@
# serializers.py
from rest_framework import serializers, permissions
from .models import Exam
class ExamSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Exam
fields = ('name', 'id', 'active', "publish_results")
permission_classes = [permissions.IsAuthenticated]
@@ -16,6 +16,11 @@
</span>
{% endfor %}
</div>
<div>
Exams: {% for exam in question.exams.all %}
<a href="{% url 'rapids:exam_overview' pk=exam.pk %}">{{ exam.name }}</a>,
{% endfor %}
</div>
<p class="pre-whitespace"><b>Feedback:</b> {{ question.feedback }}</p>
<p><b>Author(s):</b> {% for author in question.author.all %} <a
href="{% url 'rapids:author_detail' pk=author.pk %}">{{author}}</a>, {% endfor %}</p>
+59 -25
View File
@@ -8,44 +8,78 @@
<div id="view-filter-options">
<h3>Filter Rapids</h3>
<form action="" method="get">
{{ filter.form }}
<input class="btn btn-primary btn-sm mt-1 mb-1" type="submit" />
</form>
<form action="" method="get">
{{ filter.form }}
<input class="btn btn-primary btn-sm mt-1 mb-1" type="submit" />
</form>
</div>
{% render_table table %}
<button id="button-select-add-exam"></button>
<button id="button-select-add-exam" data-exam_list_url="{% url 'generic:rapid-exams-list' %}">Add selected questions to
exam</button>
<div id="exam-options"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#button-select-add-exam").click(function () {
$("#button-select-add-exam").click(function (evt) {
// Find selected objects
$.ajax({
url: "{% url 'generic:generic_exam_json_edit' %}",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
add_exam_questions: $("table input:checked").serialize(),
type: "rapid",
exam_id: exam_id,
},
type: "POST",
dataType: "json",
var jqxhr = $.get(evt.target.dataset.exam_list_url, function (data) {
console.log(data);
data.forEach((obj, n) => {
$("#exam-options").append($(document.createElement('button')).prop({
type: 'button',
innerHTML: obj.name,
class: '',
}).data("exam-id", obj.id).click((evt) => { addToExam(evt) }))
})
})
// $.ajax().done(), $.ajax().fail(), $ajax().always() are upto you. Add/change accordingly
.done(function (data) {
console.log(data);
if (data.status == "success") {
toastr.info('Questions added to exams.')
}
.done(function () {
//alert( "second success" );
})
.fail(function () {
//alert( "error" );
})
.always(function () {
console.log('[Done]');
//alert( "finished" );
});
return;
function addToExam(evt) {
ids = []
$("table input:checked").each((n, el) => {
ids.push(el.value)
})
$.ajax({
url: "{% url 'generic:generic_exam_json_edit' %}",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
add_exam_questions: JSON.stringify(ids),
type: "rapid",
exam_id: $(evt.target).data("exam-id"),
},
type: "POST",
dataType: "json",
})
// $.ajax().done(), $.ajax().fail(), $ajax().always() are upto you. Add/change accordingly
.done(function (data) {
console.log(data);
if (data.status == "success") {
toastr.info('Questions added to exams.')
}
})
.always(function () {
console.log('[Done]');
$("#exam-options").empty();
})
}
})
+11 -1
View File
@@ -65,6 +65,12 @@ from django.forms.models import model_to_dict
from rapids.forms import RapidCreationDefaultForm
from rapids.models import RapidCreationDefault
from rest_framework import viewsets
from .serializers import ExamSerializer
logger = logging.getLogger(__name__)
@@ -875,4 +881,8 @@ class QuestionDelete(AuthorOrCheckerRequiredMixin, DeleteView):
model = Rapid
success_url = reverse_lazy("rapids:rapid_view")
RapidExamViews = ExamViews(Exam, Rapid, "rapids", "rapid", loadJsonAnswer)
RapidExamViews = ExamViews(Exam, Rapid, "rapids", "rapid", loadJsonAnswer)
class ExamViewSet(viewsets.ModelViewSet):
queryset = Exam.objects.all().order_by('name')
serializer_class = ExamSerializer