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 2 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
37 changes: 34 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,9 @@ 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': 'Imie, nazwisko, numer indeksu'}))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
widget=forms.TextInput(attrs={'placeholder': 'Imie, nazwisko, numer indeksu'}))
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 +81,13 @@ 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 +100,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
71 changes: 71 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,74 @@ <h1 class="d-inline-block">
{% render_bundle 'theses-theses-change' %}
{% endif %}
</div>

<script>
$(document).ready(function() {
let previousInput;
let selectedStudentIds = [];

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: '{% url "theses:get_data" %}',
type: 'GET',
data: {
'input_value': inputValue,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (data) {
$('#id_all_students').html(data.filtered_students);
},
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);
});
</script>

{% 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'),
]
17 changes: 17 additions & 0 deletions zapisy/apps/theses/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,23 @@ def edit_thesis(request, id):
'old_instance': thesis_dict
})

from django.http import JsonResponse
from django.db.models import Q

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_html = ""
for student in filtered:
students_html += f"<option value='{student.pk}'>{student.user.get_full_name()} ({student.matricula})</option>"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Z wielu powodów dobrze byłoby, gdyby ten widok nie budował od razu fragmentu HTML. Skoro i tak zwracamy JSONa, to niech to będzie kolekcja obiektów z informacjami o studentach, którą odbierający skrypt przetworzy na odpowiednie poddrzewo DOM.


return JsonResponse({'filtered_students': students_html})

@employee_required
def new_thesis(request):
Expand Down
Loading