def view_association_requests(request, **kwargs): if request.is_ajax(): user_type = kwargs.pop('user_type') profile = kwargs.pop('profile') associations = Association.objects.filter( ~Q(initiator=user_type) ) if user_type == 'C': associations = associations.filter( Q(college=profile) & Q(approved=None) ) elif user_type == 'F': if not request.user.groups.filter(name='Placement Handler'): return JsonResponse(status=403, data={'error': 'Permission Denied. You are not authorized to handle college\'s placements.'}) associations = associations.filter( Q(college=profile.college) & Q(approved=None) & Q(initiator='CO') ) else: associations = associations.filter( Q(company=profile) & Q(approved=None) ) associations_list = [] context = {} for ass in associations: streams = ', '.join([s['name'] for s in ass.streams.values('name')]) associations_list.append({'obj':ass, 'hashid':settings.HASHID_ASSOCIATION.encode(ass.pk), 'streams': streams}) context['associations'] = associations_list if user_type in ['C','F']: html = render(request, 'college/association_requests.html', context).content.decode('utf-8') return JsonResponse(status=200, data={'html': html}) else: html = render(request, 'company/association_requests.html', context).content.decode('utf-8') return JsonResponse(status=200, data={'html': html}) else: return handle_user_type(request, redirect_request=True)
def company_signup(request): if not request.recaptcha_is_valid: return JsonResponse( status=400, data={ 'error': 'reCAPTCHA authorization failed. Please try again.' }) if request.user.is_authenticated(): return handle_user_type(request, redirect_request=True) f = SignupForm(request.POST) f.instance.type = 'CO' if f.is_valid(): user = f.save(user_type='CO') user = authenticate(username=f.cleaned_data['username'], password=f.cleaned_data['password2']) # auth_login(request, user) send_activation_email_task.delay(user.pk, get_current_site(request).domain) context = { 'user': user, 'email': user.email, 'profile_creation': request.build_absolute_uri( reverse(settings.PROFILE_CREATION_URL['CO'])) } html = render(request, 'account/post_signup.html', context).content.decode('utf-8') return JsonResponse(data={'success': True, 'render': html}) else: return JsonResponse(status=400, data={'errors': dict(f.errors.items())})
def edit_college(request, **kwargs): if request.is_ajax(): ## if request.user.type == 'C': try: college = request.user.college except College.DoesNotExist: return JsonResponse(status=400, data={'location': reverse(settings.PROFILE_CREATION_URL['C'])}) f = CollegeEditForm(request.POST, request.FILES, instance=college) photo = college.photo if f.is_valid(): f.save() if photo and photo != college.photo: try: os.remove(os.path.join(settings.BASE_DIR, photo.url[1:])) except: pass context = {} context['edit_college_form'] = CollegeEditForm(instance=college) if f.has_changed(): context['success_msg'] = "Profile has been updated successfully!" return JsonResponse(status=200, data={'render': render(request, 'college/edit.html', context).content.decode('utf-8')}) else: return JsonResponse(status=400, data={'errors': dict(f.errors.items())}) ## else: ## return JsonResponse(status=400, data={'location': get_relevant_reversed_url(request)}) else: return handle_user_type(request, redirect_request=True)
def edit_create_faculty(request, **kwargs): if request.is_ajax(): if request.user.type == 'F' and request.method == 'POST': faculty = request.user.faculty f = FacultyProfileForm(request.POST, request.FILES, instance=faculty) photo = faculty.photo if f.is_valid(): f.save() if photo and photo != faculty.photo: try: os.remove( os.path.join(settings.BASE_DIR, photo.url[1:])) except: pass context = {} context['faculty_edit_form'] = FacultyProfileForm( instance=faculty) if f.has_changed(): context[ 'success_msg'] = "Profile has been updated successfully!" return JsonResponse(status=200, data={ 'render': render(request, 'faculty/profile_form.html', context).content.decode('utf-8') }) else: return JsonResponse(status=400, data={'errors': dict(f.errors.items())}) else: return JsonResponse( status=400, data={'location': get_relevant_reversed_url(request)}) else: # To handle initial creation form if request.user.type == 'F': context = {} if request.method == 'GET': f = FacultyProfileForm(instance=request.user.faculty) else: f = FacultyProfileForm(request.POST, request.FILES, instance=request.user.faculty) if f.is_valid(): f.save() if f.has_changed(): context['update'] = True return redirect(settings.HOME_URL['F']) context['faculty_edit_create_form'] = f return render(request, 'faculty/edit_create.html', context) else: return handle_user_type(request, redirect_request=True)
def stats(request): if request.user.is_authenticated(): return handle_user_type(request, redirect_request=True) if request.is_ajax(): if request.GET.get('years', '') == 'true': try: college = College.objects.prefetch_related('records').get(pk=request.GET.get('college', None)) years = [c['academic_year'] for c in college.records.values('academic_year')] data = [] for year in years: data.append({'html': year, 'value': year}) return JsonResponse(status=200, data={'years': data}) except: return JsonResponse(status=400, data={'errors': 'Please choose a valid college.'}) elif request.GET.get('stats', '') == 'true': college_pk = request.GET.get('college', None) year = request.GET.get('year', None) if not year or not college_pk: message = 'Invalid ' + ('college chosen' if not college_pk else 'year chosen') return JsonResponse(status=400, data={'errors': message}) # Table headings = ['Company', 'Type', 'Total Offerings', 'Salary (LPA)'] college = College.objects.prefetch_related('records').get(pk=college_pk) record = college.records.get(academic_year=year) placements = record.placements.order_by('-salary').all() entries = [] for each in placements: company = each.company.name type = dict(Placement.PLACEMENT_TYPE)[each.type] offered = each.total_offers or '---' #if each.total_offers else 'Result Awaited' salary = each.salary_comment if each.salary_comment else ('Training' if not each.salary and type.lower().startswith('i') else each.salary) entries.append([company, type, offered, salary]) context = {'headings': headings, 'entries': entries} table = render(request, 'stats/table.html', context).content.decode('utf-8') # # # # Graph graph = [] for each in placements: if each.salary_comment: continue point = {} point['salary'] = float(each.salary) point['offers'] = each.total_offers point['company'] = each.company.name graph.append(point) # # # return JsonResponse(status=200, data={'table': table, 'graph': graph}) else: return JsonResponse(status=400, data={'errors': 'Please choose from the options.'}) else: context = {'stats_form': StatsForm()} return render(request, 'stats/stats.html', context)
def decline(request, **kwargs): user_type = kwargs.get('user_type') if request.is_ajax(): if user_type == 'F' and not request.user.groups.filter(name='Placement Handler'): return JsonResponse(status=403, data={'error': 'Permission Denied. You are not authorized to handle college\'s placements.'}) if request.method == 'GET': try: association_id = settings.HASHID_ASSOCIATION.decode(request.GET.get('ass'))[0] association = Association.objects.prefetch_related('college', 'company').get(pk=association_id) except: return JsonResponse(status=400, data={'error': 'Unexpected error occurred. Please refresh the page and try again'}) f = DeclineForm(association=association) context = {'decline_form': f} context['association'] = association context['other_party'] = association.company.name if association.initiator == 'CO' else association.college.name context['streams'] = ', '.join([s['name'] for s in association.streams.values('name')]) context['hashid'] = settings.HASHID_ASSOCIATION.encode(association.pk) html = render(request, 'recruitment/decline.html', context).content.decode('utf-8') return JsonResponse(status=200, data={'html':html}) else: POST = request.POST.copy() try: association_id = settings.HASHID_ASSOCIATION.decode(request.POST.get('token'))[0] association = Association.objects.prefetch_related('college', 'company').get(pk=association_id) except: return JsonResponse(status=400, data={'error': 'Unexpected error occurred. Please refresh the page and try again'}) POST['college'] = association.college.pk POST['company'] = association.company.pk f = DeclineForm(POST, association=association) if f.is_valid(): f.save() # LOG if user_type == 'C': message = "[%s: %s] -> Declined Request -> [%s] - [%d]" % \ (association.college.profile.username, association.college.code, association.company.name, association.pk) else: message = "[%s: %s] -> Declined Request -> [%s] - [%d]" % \ (association.company.profile.username, association.company.name, association.college.profile.username, association.pk) recruitmentLogger.info(message) # # # message = 'You declined the request.\nIf you wish to stop receiving requests from this user, you can block them.\n Click info to know more.' return JsonResponse(status=200, data={'refresh': True, 'message': message}) else: return JsonResponse(status=400, data={'errors': dict(f.errors.items()), 'message': 'Please correct the errors as indicated in the form.'}) else: return handle_user_type(request, redirect_request=True)
def create_company(request, **kwargs): if request.user.type == 'CO': if request.method == 'GET': f = CompanyCreationForm() try: company = request.user.company return redirect(settings.HOME_URL['CO']) except Company.DoesNotExist: pass else: f = CompanyCreationForm(request.POST, request.FILES) if f.is_valid(): company = f.save(profile=request.user) return redirect(settings.HOME_URL['CO']) return render(request, 'company/create.html', {'company_creation_form': f}) else: return handle_user_type(request, redirect_request=True)
def faculty_signup(request): user = request.user if request.is_ajax(): if user.type == 'C': f = FacultySignupForm(request.POST) f.instance.type = 'F' if f.is_valid(): faculty = f.save() f.save_m2m() Faculty.objects.create(profile=faculty, college=user.college) collegeLogger.info( '[%s] - %s added faculty %s' % (user.college.code, user.username, faculty.username)) send_activation_email_task.delay( faculty.pk, get_current_site(request).domain) message = 'Faculty %s has been added.' % (faculty.username) return JsonResponse(status=200, data={ 'location': reverse(settings.HOME_URL['C']), 'refresh': True, message: message }) else: return JsonResponse( status=400, data={ 'errors': dict(f.errors.items()), 'message': 'Please correct the errors as indicated in the form.' }) else: return JsonResponse(status=400, data={ 'location': get_relevant_reversed_url(request), 'refresh': True }) else: return handle_user_type(request, redirect_request=True)
def college_signup(request): if request.user.is_anonymous: return redirect('landing') if request.user.is_authenticated(): return handle_user_type(request, redirect_response=True) if request.method == 'GET': f = SignupForm() else: f = SignupForm(request.POST) f.instance.type = 'C' if f.is_valid(): college = f.save(user_type='C') college = authenticate(username=f.cleaned_data['username'], password=f.cleaned_data['password2']) context = {} if college: # auth_login(request, college) context['email'] = college.email context['profile_creation'] = request.build_absolute_uri(reverse(settings.PROFILE_CREATION_URL['C'])) send_activation_email_task.delay(college.pk, get_current_site(request).domain) return render(request, 'account/post_signup.html', context) return render(request, 'college/signup.html', {'college_signup_form': f})
def past_recruiters(request): if request.user.is_authenticated(): return handle_user_type(request, redirect_request=True) try: get_template('stats/past_recruiters_compiled.html') return render(request, 'stats/past_recruiters_compiled.html', {}) # optimization except: pass queryset = Company.objects.all().order_by('name') half = queryset.count()/2 i,j = 0,0 ones = queryset[:half] twos = queryset[half:] companies = [] while i < len(ones) or j < len(twos): data = {} try: data['one'] = ones[i] except IndexError: pass try: data['two'] = twos[j] except IndexError: pass i = i+1 j = j+1 companies.append(data) r = render(request, 'stats/past_recruiters.html', {'companies': companies}) # compiling the data to a template because the data to be displayed is constant for long time # so why hit the db content = r.content.decode('utf-8') f = open('templates/stats/past_recruiters_compiled.html', 'w') try: f.write(content) finally: f.close() return r
def mysessions(request): if request.is_ajax(): user = request.user type = user.type sessions = None; html='' if type == 'S': try: student = user.student except Student.DoesNotExist: return JsonResponse(status=400, data={'location': reverse(settings.PROFILE_CREATION_URL['S'])}) sessions = student.sessions.all() dsessions = student.dummy_sessions.all() all_sessions_list = [] for s in sessions: assoc = s.association data = {} data['sessobj'] = s data['sessid'] = settings.HASHID_PLACEMENTSESSION.encode(s.pk) data['salary'] = "%d LPA" % assoc.salary data['company'] = assoc.company.name.title() if assoc.company.name.islower() else assoc.company.name data['type'] = "Internship" if assoc.type == 'I' else "Job" data['photo'] = assoc.company.photo data['streams'] = ', '.join([s.name.title() for s in assoc.streams.all()]) data['programme'] = assoc.programme data['years'] = assoc.session.selection_criteria.years data['students'] = s.students.count() data['status'] = s.status data['is_dummy'] = False all_sessions_list.append(data) for ds in dsessions: data = {} data['dsessobj'] = ds data['dsessid'] = settings.HASHID_DUMMY_SESSION.encode(ds.pk) data['salary'] = "%d LPA" % ds.salary data['company'] = ds.dummy_company.name.title() if ds.dummy_company.name.islower() else ds.dummy_company.name data['type'] = "Internship" if ds.type == 'I' else "Job" data['streams'] = ', '.join([s.name.title() for s in ds.streams.all()]) data['programme'] = ds.programme data['years'] = ds.selection_criteria.years data['students'] = ds.students.count() data['status'] = ds.status data['is_dummy'] = True all_sessions_list.append(data) html = render(request, 'student/mysessions.html', {'sessions': all_sessions_list}).content.decode('utf-8') elif type == 'CO': try: company = user.company except Company.DoesNotExist: return JsonResponse(status=400, data={'location': reverse(settings.PROFILE_CREATION_URL['CO'])}) associations = Association.objects.filter(company=company, approved=True).values('pk') sessions = PlacementSession.objects.filter(association__pk__in = associations) sessions_list = [] for s in sessions: assoc = s.association data = {} data['sessobj'] = s data['sess_hashid'] = settings.HASHID_PLACEMENTSESSION.encode(s.pk) data['salary'] = "%d LPA" % assoc.salary data['college'] = assoc.college.name.title() data['type'] = "Internship" if assoc.type == 'I' else "Job" data['photo'] = assoc.college.photo data['streams'] = ', '.join([s.name.title() for s in assoc.streams.all()]) data['programme'] = assoc.programme data['years'] = assoc.session.selection_criteria.years data['students'] = s.students.count() sessions_list.append(data) html = render(request, 'company/mysessions.html', {'sessions': sessions_list}).content.decode('utf-8') else: college = None if type == 'F': verdict = False try: faculty = user.faculty except Faculty.DoesNotExist: verdict = True if not faculty.firstname: verdict = True if verdict: return JsonResponse(status=400, data={'location': reverse(settings.PROFILE_CREATION_URL['F'])}) if not request.user.groups.filter(name__in=['Placement Handler', 'Notifications Manager']): return JsonResponse(status=403, data={'error': 'Permission Denied. You are not authorized to handle college\'s placements.'}) college = faculty.college elif type == 'C': try: college = user.college except College.DoesNotExist: return JsonResponse(status=400, data={'location': reverse(settings.PROFILE_CREATION_URL['C'])}) associations = Association.objects.filter(college=college, approved=True).values('pk') sessions = PlacementSession.objects.filter(association__pk__in = associations, ended=False) dsessions = DummySession.objects.filter(dummy_company__college=college, ended=False) sessions_list = [] dsessions_list = [] for s in sessions: assoc = s.association data = {} data['sessobj'] = s data['sess_hashid'] = settings.HASHID_PLACEMENTSESSION.encode(s.pk) data['salary'] = "%d LPA" % assoc.salary data['company'] = assoc.company.name.title() data['type'] = "Internship" if assoc.type == 'I' else "Job" data['photo'] = assoc.company.photo data['streams'] = ', '.join([s.name.title() for s in assoc.streams.all()]) data['programme'] = assoc.programme data['years'] = assoc.session.selection_criteria.years data['students'] = s.students.count() # data['is_dummy'] = False sessions_list.append(data) for ds in dsessions: data = {} data['dsessobj'] = ds data['dsess_hashid'] = settings.HASHID_DUMMY_SESSION.encode(ds.pk) data['salary'] = "%d LPA" % ds.salary data['dcompany'] = ds.dummy_company.name.title() data['type'] = "Internship" if ds.type == 'I' else "Job" data['streams'] = ', '.join([s.name.title() for s in ds.streams.all()]) data['programme'] = ds.programme data['years'] = ds.selection_criteria.years data['students'] = ds.students.count() # data['is_dummy'] = True dsessions_list.append(data) html = render(request, 'college/mysessions.html', {'sessions': sessions_list, 'dsessions': dsessions_list}).content.decode('utf-8') return JsonResponse(status=200, data={'html': html}) else: return handle_user_type(request)
def create_session(request, **kwargs): if request.is_ajax(): type = kwargs.pop('user_type') if type == 'F' and not request.user.groups.filter(name='Placement Handler'): return JsonResponse(status=403, data={'error': 'Permission Denied. You are not authorized to handle college\'s placements.'}) if request.method == 'GET': try: association_id = settings.HASHID_ASSOCIATION.decode(request.GET.get('ass'))[0] association = Association.objects.get(pk=association_id) except: #To account for both KeyError as well as Association.DoesNotExist return JsonResponse(status=400, data={'error': 'Invalid Request.'}) # validating whether the college/company is making request for its own association requester = validate_associator(request, association) creation = requester.get('creation', False) if creation: return JsonResponse(status=400, data={'location': creation}) if not requester.get('authorized', True): return JsonResponse(status=403, data={'error': 'You cannot make this request.'}) if association.initiator == type: # Validating that the requester is not the one accepting return JsonResponse(status=400, data={'error': 'You cannot make this request.'}) f = CreateSessionCriteriaForm(association=association) context = {'session_creation_form': f} context['association'] = association context['other_party'] = association.company.name if association.initiator == 'CO' else association.college.name context['streams'] = ', '.join([s['name'] for s in association.streams.values('name')]) context['hashid'] = settings.HASHID_ASSOCIATION.encode(association.pk) html = render(request, 'recruitment/create_session.html', context).content.decode('utf-8') return JsonResponse(status=200, data={'html':html}) else: user_type = kwargs.get('user_type') try: association_id = settings.HASHID_ASSOCIATION.decode(request.POST.get('token'))[0] association = Association.objects.prefetch_related('college', 'company').get(pk=association_id) except: return JsonResponse(status=400, data={'error': 'Invalid Request.'}) # validating whether the college/company is making request for its own association requester = validate_associator(request, association) creation = requester.get('creation', False) if creation: return JsonResponse(status=400, data={'location': creation}) if not requester.get('authorized', True): return JsonResponse(status=403, data={'error': 'You cannot make this request.'}) if association.initiator == type: # Validating that the requester is not the one accepting return JsonResponse(status=400, data={'error': 'You cannot make this request.'}) try: association.session return JsonResponse(status=400, data={'error': 'Session already exists', 'refresh': True}) except PlacementSession.DoesNotExist: pass # Converting list to string. i.e. somewhat custom to_python POST = request.POST.copy() POST['years'] = (','.join(POST.getlist('years'))) f = CreateSessionCriteriaForm(POST, association=association) if f.is_valid(): data = f.cleaned_data criterion,created = SelectionCriteria.objects.get_or_create(years=data['years'], is_sub_back=data['is_sub_back'], tenth=data['tenth'], twelfth=data['twelfth'], graduation=data['graduation'], post_graduation=data['post_graduation'], doctorate=data['doctorate']) session = PlacementSession.objects.create(association=association,application_deadline=data['application_deadline'],last_modified_by=type, selection_criteria=criterion) association.approved = True association.save() # LOG if user_type == 'C': message = "[%s] -> Created Session (Accepted) -> [%s] - [A/S: %d/%d]" % \ (association.college.code, association.company.name, association.pk, session.pk) else: message = "[%s: %s] -> Created Session (Accepted) -> [%s] - [A/S: %d/%d]" % \ (association.company.profile.username, association.company.name, association.college.code, association.pk, session.pk) recruitmentLogger.info(message) # # # message = '%s session has been created successfully. To manage the session, move to "Sessions" tab.'\ % (dict(Association.PLACEMENT_TYPE)[association.type]) return JsonResponse(status=200, data={'refresh': True, 'message': message}) else: return JsonResponse(status=400, data={'errors': dict(f.errors.items()), 'message': 'Please correct the errors as indicated in the form.'}) else: return handle_user_type(request, redirect_request=True)