Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1586 szybsze i wygodniejsze wybieranie studentow do tematu pracy dyplomowej #1704

Open
wants to merge 6 commits into
base: master-dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions zapisy/apps/theses/assets/theses-filter-students.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
$(document).ready(function () {
let previousInput;
let selectedStudentIds = $("#id_students option")
.map(function () {
return $(this).val();
})
.get();
$("#id_selected_students").val(selectedStudentIds.join(","));
$("#id_students").find("option:selected").prop("selected", false);

function debounce(func, delay) {
let timer;
return function () {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
func.apply(context, args);
}, delay);
};
}

function handleInput() {
const inputValue = $("#id_user_input").val().trim();

if (inputValue === previousInput || inputValue === "") {
return;
}
previousInput = inputValue;

$.ajax({
url: ajaxUrl,
type: "GET",
data: {
input_value: inputValue,
csrfmiddlewaretoken: csrfToken,
},
success: function (data) {
const students = data.filtered_students;
const allStudentsElement = $("#id_all_students");
const pickedStudentIds = $("#id_students option")
.map(function () {
return $(this).val();
})
.get();

allStudentsElement.empty();
students.forEach(function (student) {
if (!pickedStudentIds.includes(student.id.toString())) {
allStudentsElement.append(
`<option value='${student.id}'>${student.name} (${student.matricula})</option>`
);
}
});
},
error: function (xhr, status, error) {
console.error("Something went wrong :(");
},
});
}

function updateSelectedStudents() {
const all_students = $("#id_all_students");
const picked_students = $("#id_students");

picked_students.find("option:selected").each(function () {
all_students.append($(this).clone().prop("selected", false));
const student_id = $(this).val();
const index = selectedStudentIds.indexOf(student_id);
selectedStudentIds.splice(index, 1);
$(this).remove();
});

all_students.find("option:selected").each(function () {
picked_students.append($(this).clone().prop("selected", false));
selectedStudentIds.push($(this).val());
$(this).remove();
});
$("#id_selected_students").val(selectedStudentIds.join(","));
console.log("Selected Student IDs:", selectedStudentIds);
console.log("Hidden input value:", $("#id_selected_students").val());
}

const debouncedInputHandler = debounce(handleInput, 200);
$("#id_user_input").on("input", debouncedInputHandler);
$("#id_all_students, #id_students").on("change", updateSelectedStudents);
});
44 changes: 41 additions & 3 deletions zapisy/apps/theses/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,15 @@ class Meta:
label="Promotor wspierający",
required=False)
kind = forms.TypedChoiceField(choices=ThesisKind.choices, label="Typ", coerce=int)
all_students = forms.ModelMultipleChoiceField(
queryset=Student.objects.none(),
required=False,
label="Studenci",
widget=forms.SelectMultiple(attrs={'size': '10'}))
students = forms.ModelMultipleChoiceField(
queryset=Student.objects.all(),
queryset=Student.objects.none(),
required=False,
label="Przypisani studenci",
label="Wybrani studenci",
widget=forms.SelectMultiple(attrs={'size': '10'}))
reserved_until = forms.DateField(help_text="Jeżeli przypiszesz do pracy studentów, "
"uzupełnij również datę rezerwacji.",
Expand All @@ -58,6 +63,13 @@ class Meta:
label="Maks. liczba studentów", coerce=int,
choices=tuple((i, i) for i in range(1, MAX_MAX_ASSIGNED_STUDENTS + 1))
)
user_input = forms.CharField(
label="Znajdź studenta",
max_length=30,
required=False,
widget=forms.TextInput(attrs={'placeholder': 'Filtruj po imieniu, nazwisku, numerze indeksu'})
)
selected_students = forms.CharField(widget=forms.HiddenInput(), required=False)

def __init__(self, user, *args, **kwargs):
super(ThesisFormBase, self).__init__(*args, **kwargs)
Expand All @@ -73,6 +85,12 @@ def __init__(self, user, *args, **kwargs):

self.fields['status'].required = False

if 'selected_students' in self.data:
selected_student_ids = [int(sid) for sid in self.data.get('selected_students').split(',') if sid.isdigit()]
self.update_students_queryset(Student.objects.filter(id__in=selected_student_ids))
self.data = self.data.copy()
self.data.setlist('students', selected_student_ids)

self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.layout = Layout(
Expand All @@ -85,13 +103,29 @@ def __init__(self, user, *args, **kwargs):
Column('max_number_of_students', css_class='form-group col-md-3'),
Column('reserved_until', css_class='form-group col-md-6'),
css_class='row'),
'students',
'user_input',
Row(
Column('all_students', css_class='form-group col-md-6'),
Column('students', css_class='form-group col-md-6'),
css_class='row'),
'description',
)
self.helper.add_input(
Submit('submit', 'Zapisz', css_class='btn-primary'))

def update_students_queryset(self, queryset):
self.fields['students'].queryset = queryset

def clean_students(self):
selected_student_ids = self.cleaned_data.get('selected_students', '')
if selected_student_ids:
student_ids = [int(sid) for sid in selected_student_ids.split(',') if sid.isdigit()]
students = Student.objects.filter(id__in=student_ids)
return students
return []

def clean(self):
self.cleaned_data['students'] = self.clean_students()
super().clean()
students = self.cleaned_data['students']
max_number_of_students = int(self.cleaned_data['max_number_of_students'])
Expand Down Expand Up @@ -122,6 +156,10 @@ def __init__(self, user, *args, **kwargs):

self.status = self.instance.status

if self.instance and self.instance.pk:
student_ids = self.instance.students.values_list('pk', flat=True)
self.fields['students'].queryset = Student.objects.filter(pk__in=student_ids)

def save(self, commit=True):
instance = super().save(commit=False)
instance.modified = timezone.now()
Expand Down
8 changes: 8 additions & 0 deletions zapisy/apps/theses/templates/theses/thesis_form.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ <h1 class="d-inline-block">
{% endif %}

<form method="POST" id="confirm-submit" class="post-form">
<input type="hidden" id="id_selected_students" name="selected_students" value="">
{% csrf_token %}
{% crispy thesis_form %}
</form>
Expand All @@ -51,4 +52,11 @@ <h1 class="d-inline-block">
{% render_bundle 'theses-theses-change' %}
{% endif %}
</div>

<script>
const ajaxUrl = '{% url "theses:get_data" %}';
const csrfToken = '{{ csrf_token }}';
</script>
{% render_bundle 'theses-theses-filter-students' %}

{% endblock %}
1 change: 1 addition & 0 deletions zapisy/apps/theses/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@
path('<int:id>/form/<int:studentid>', views.gen_form, name="gen_form"),
path('<int:id>/rejecter', views.rejecter_decision, name="rejecter_thesis"),
path('<int:id>/delete', views.delete_thesis, name="delete_thesis"),
path('ajax/get_data/', views.get_data, name='get_data'),
]
22 changes: 21 additions & 1 deletion zapisy/apps/theses/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.http import Http404, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.http import require_POST
from django.forms.models import model_to_dict
from django.db.models import Q

from apps.theses.enums import ThesisStatus, ThesisVote
from apps.theses.forms import EditThesisForm, RejecterForm, RemarkForm, ThesisForm, VoteForm
Expand Down Expand Up @@ -214,6 +215,25 @@ def edit_thesis(request, id):
})


def get_data(request):
if request.method == 'GET':
input_value = request.GET.get('input_value', '')
filtered = Student.objects.filter(
Q(matricula__icontains=input_value) |
Q(user__first_name__icontains=input_value) |
Q(user__last_name__icontains=input_value)
)
students = [
{
'id': student.pk,
'name': student.user.get_full_name(),
'matricula': student.matricula
}
for student in filtered
]
return JsonResponse({'filtered_students': students})


@employee_required
def new_thesis(request):
"""Show form for create new thesis."""
Expand Down
3 changes: 3 additions & 0 deletions zapisy/webpack_resources/asset-defs.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ const AssetDefs = {

"theses-theses-widget": [path.resolve("apps/theses/assets/theses-widget.js")],
"theses-theses-change": [path.resolve("apps/theses/assets/theses-change.js")],
"theses-theses-filter-students": [
path.resolve("apps/theses/assets/theses-filter-students.js"),
],

// User app

Expand Down
Loading