Skip to content
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,6 @@ cron/*
creation/hr-receipts/
*.DS_Store
static/spoken/embedding/

*.sql
env/
27 changes: 25 additions & 2 deletions events/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,11 +513,34 @@ def __init__(self, *args, **kwargs):
class StudentPasswordResetForm(forms.Form):
state = forms.ModelChoiceField(queryset=State.objects.all(),
empty_label="Select State",)
school = forms.ModelChoiceField(queryset=AcademicCenter.objects.filter(institution_type_id=5))
batches = forms.ModelMultipleChoiceField(queryset=StudentBatch.objects.filter(academic__institution_type_id=5))
school = forms.ModelChoiceField(queryset=AcademicCenter.objects.none())
batches = forms.ModelMultipleChoiceField(queryset=StudentBatch.objects.none())
new_password = forms.CharField()
confirm_password = forms.CharField()

def __init__(self, *args, **kwargs):
state_id = None
school_id = None

# Extract data from args (when form is created with POST data)
if args and len(args) > 0 and hasattr(args[0], 'get'):
state_id = args[0].get('state')
school_id = args[0].get('school')
# Extract data from kwargs (when form has initial data)
elif 'initial' in kwargs:
state_id = kwargs['initial'].get('state')
school_id = kwargs['initial'].get('school')

super().__init__(*args, **kwargs)

# Set querysets based on the extracted data
if state_id:
self.fields['school'].queryset = AcademicCenter.objects.filter(state_id=state_id)
if school_id:
self.fields['batches'].queryset = StudentBatch.objects.filter(academic_id=school_id)
else:
self.fields['batches'].queryset = StudentBatch.objects.none()

def clean(self):
cleaned_data = super().clean()
new_password = cleaned_data.get('new_password')
Expand Down
2 changes: 2 additions & 0 deletions events/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from django.conf.urls import url, include
from events.views import *
from events.notification import nemail
from .views import get_schools, get_batches

app_name = 'events'
urlpatterns = [
url(r'^$', events_dashboard, name='events_dashboard'),
Expand Down
57 changes: 35 additions & 22 deletions events/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
from django.http import JsonResponse
from .models import StudentBatch
from django.urls import reverse

def get_batches(request):
school_id = request.GET.get('school_id')
if school_id:
batches = StudentBatch.objects.filter(academic_id=school_id).values('id', 'batch_name')
return JsonResponse(list(batches), safe=False)
return JsonResponse([])

from django.core.exceptions import PermissionDenied

from django.contrib.auth.decorators import login_required
Expand Down Expand Up @@ -1344,7 +1355,7 @@ def training_clone(request, role, rid = None):
messages.error(request, "You have already scheduled <b>"+ str(request.POST['tdate']) + "</b> training on <b>"+ str(master_training.tdate) + "</b>. Please select some other date.")


if not csv_file_error:# and request.POST.get('remove-error')):
if not csv_file_error:# and request.POST.get('remove-error'):
existing_emails = None
if reattempt_list and more_then_two_per_day_list:
existing_emails = set(reattempt_list.split(',')).union(set(more_then_two_per_day_list.split(',')))
Expand Down Expand Up @@ -2318,8 +2329,10 @@ def test_participant_ceritificate(request, wid, participant_id):
# Draw image on Canvas and save PDF in buffer
imgPath = get_signature(ta.test.tdate)
imgDoc.drawImage(imgPath, 600, 95, 150, 76) ## at (399,760) with size 160x160

credits = "<p><b>Credits:</b> "+str(w.foss.credits)+"&nbsp&nbsp&nbsp<b>Score:</b> "+str('{:.2f}'.format(mdlgrade.grade))+"%</p>"

#paragraphe
text = get_test_cert_text(ta.test, mdluser, credits=credits)
centered = ParagraphStyle(name = 'centered',
fontSize = 15,
Expand All @@ -2331,7 +2344,6 @@ def test_participant_ceritificate(request, wid, participant_id):
p.wrap(700, 200)
p.drawOn(imgDoc, 3 * cm, 6.5 * cm)


#paragraphe
text = "Certificate for the Completion of <br/>"+w.foss.foss+" Training"

Expand All @@ -2351,7 +2363,6 @@ def test_participant_ceritificate(request, wid, participant_id):
# Use PyPDF to merge the image-PDF into the template
template_path = get_test_certificate(ta)
page = PdfFileReader(open(template_path,"rb")).getPage(0)

overlay = PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0)
page.mergePage(overlay)

Expand Down Expand Up @@ -2859,13 +2870,13 @@ def ajax_district_data(request):
tmp +='<option value='+str(i.id)+'>'+i.name+'</option>'
data['location'] = tmp

if request.POST.get('fields[institute]'):
collages = AcademicCenter.objects.filter(district=district).order_by('institution_name')
if collages:
tmp = '<option value = None> -- None -- </option>'
for i in collages:
tmp +='<option value='+str(i.id)+'>'+i.institution_name+'</option>'
data['institute'] = tmp
if request.POST.get('fields[institute]'):
collages = AcademicCenter.objects.filter(district=district).order_by('institution_name')
if collages:
tmp = '<option value = None> -- None -- </option>'
for i in collages:
tmp +='<option value='+str(i.id)+'>'+i.institution_name+'</option>'
data['institute'] = tmp

return HttpResponse(json.dumps(data), content_type='application/json')

Expand Down Expand Up @@ -3219,13 +3230,16 @@ def reset_student_pwd(request):
template = 'events/templates/reset_student_password.html'
form = StudentPasswordResetForm()
context['form'] = form

if request.method == "POST":
form = StudentPasswordResetForm(request.POST)
context['form'] = form

if form.is_valid():
school = form.cleaned_data['school']
batches = form.cleaned_data['batches']
new_password = form.cleaned_data['new_password']

batch_ids = [x.id for x in batches]
batches = StudentBatch.objects.filter(id__in=batch_ids)
student_ids = StudentMaster.objects.filter(batch__in=batches).values_list('student_id', flat=True)
Expand All @@ -3238,28 +3252,27 @@ def reset_student_pwd(request):
emails = [user.email for user in users]
mdlUsers = MdlUser.objects.filter(email__in=emails)
mdlUsers.update(password=encript_password(new_password))
send_bulk_student_reset_mail(school,batches,users.count(), new_password,request.user)
messages.add_message(request, messages.SUCCESS, f"Password updated for {users.count()} students.")
send_bulk_student_reset_mail(school,batches,users.count(), new_password,request.user)

# Add the success message
success_msg = "Password updated for {} students.".format(users.count())
messages.success(request, success_msg)


redirect_url = reverse('events:reset_student_pwd')
return HttpResponseRedirect(redirect_url)
return render(request,template,context)


def get_schools(request):
state_id = request.GET.get('state_id')
if state_id:
schools = AcademicCenter.objects.filter(
institution_type_id=5, state_id=state_id,
state_id=state_id,
studentbatch__isnull=False).distinct().values(
'id', 'institution_name', 'academic_code').order_by('institution_name') # 5 for school
'id', 'institution_name', 'academic_code').order_by('institution_name')
return JsonResponse(list(schools), safe=False)
return JsonResponse([])


def get_batches(request):
school_id = request.GET.get('school_id')
if school_id:
batches = StudentBatch.objects.filter(academic_id=school_id).values('id', 'batch_name')
return JsonResponse(list(batches), safe=False)
return JsonResponse([])



14 changes: 7 additions & 7 deletions static/events/templates/reset_student_password.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@
</div>
<div class="form-group">
<label>Batches:</label>
{% render_field form.batches class+="form-control" multiple="multiple" %}
<select id="id_batches" name="batches" class="form-control" multiple>
<option value="">Select Batch</option>
</select>
</div>
<div class="form-group">
<label>New Password</label>
Expand Down Expand Up @@ -105,22 +107,20 @@
// Fetch batches based on selected school
$("#id_school").change(function(){
let schoolId = $(this).val();
let batchSelect = $("#id_batches");
batchSelect.empty().append('<option value="">Select Batch</option>');
if(!schoolId) return;

fetch(`{% url 'events:get_batches' %}?school_id=${schoolId}`)
.then(response => response.json())
.then(data => {
let batchSelect = $("#id_batches");
batchSelect.empty();
data.forEach(batch => {
batchSelect.append(`<option value="${batch.id}">${batch.id}-${batch.batch_name}</option>`);
batchSelect.append(`<option value="${batch.id}">${batch.batch_name}</option>`);
})
})
.catch(error => {
alert('an error occurred')
});

})
});
})
</script>
{% endblock %}