def showform(request): if 'username' not in request.session: print "No session" request.session['redirect'] = request.get_full_path() return our_redirect('/ldap_login') prn = request.session['username'] #the user shoud not get the form if he already has one. try: s = student.objects.get(pk=request.session['username']) print "student Fornd...", s return our_redirect('/student_info/%d/edit' % prn) except Exception as e: print "student does not exist" if prn.isdigit(): yr = prn[5:7] else: yr = 'staff' print yr maintable = list( companySpecific.objects.exclude( fieldType='special').order_by('displayText')) print(maintable) t = loader.get_template('student_info/form.html') c = RequestContext(request, { 'flag': 'form', 'prn': prn, 'ROOT': ROOT, 'mt': maintable, 'yr': yr }) return HttpResponse(t.render(c))
def showform(request): if 'username' not in request.session: print "No session" request.session['redirect'] = request.get_full_path(); return our_redirect('/ldap_login') prn=request.session['username']; #the user shoud not get the form if he already has one. try: s=student.objects.get(pk=request.session['username']) print "student Fornd...", s return our_redirect('/student_info/%d/edit' % prn); except Exception as e: print "student does not exist" if prn.isdigit(): yr=prn[5:7]; else: yr = 'staff' print yr maintable=list(companySpecific.objects.exclude(fieldType='special').order_by('displayText')); print(maintable); t=loader.get_template('student_info/form.html') c=RequestContext(request, { 'flag':'form', 'prn':prn, 'ROOT':ROOT, 'mt':maintable, 'yr':yr } ); return HttpResponse(t.render(c));
def ajaxRequest(request): '''for processing any ajax request for a field data''' '''will accept data in XML (ok?) and return data in XML ''' pass; return our_redirect('/student_info/%d/edit' %(int(request.session['username']))) return HttpResponse('you arent supposed to see this page. if u see this please contact apoorva')
def apply(request): print request.POST #check for the session and our_redirect if 'username' not in request.session: request.session['redirect'] = request.get_full_path(); return our_redirect('/ldap_login/') prn=request.session['username'] # check for only three entries in POST except for csrfmiddlewaretoken if len(request.POST) >4: # onr extra for csrf... return HttpResponse('More than Three companies :)') # fetch student of ths prn try: s = student.objects.get(pk=prn) except Exception as e: output = "<h3>Fill in ur details first</h3>"; return HttpResponse(output); # make a list f the companies ths student had applied to pehle c=company.objects.filter(students_applied=s) #take each company from POST for k in request.POST.keys(): if k == 'csrfmiddlewaretoken': continue; applied_company=company.objects.get(name=k) # if already applied if applied_company in c: continue; else: applied_company.students_applied.add(s); applied_company.save(); #add this student to the list of applied_students #save # if unchecked.. then remove. for k in c: if k.name in request.POST.keys(): continue else: k.students_applied.remove(s) k.save(); return our_redirect('/common/company/done');
def apply(request): print request.POST #check for the session and our_redirect if 'username' not in request.session: request.session['redirect'] = request.get_full_path() return our_redirect('/ldap_login/') prn = request.session['username'] # check for only three entries in POST except for csrfmiddlewaretoken if len(request.POST) > 4: # onr extra for csrf... return HttpResponse('More than Three companies :)') # fetch student of ths prn try: s = student.objects.get(pk=prn) except Exception as e: output = "<h3>Fill in ur details first</h3>" return HttpResponse(output) # make a list f the companies ths student had applied to pehle c = company.objects.filter(students_applied=s) #take each company from POST for k in request.POST.keys(): if k == 'csrfmiddlewaretoken': continue applied_company = company.objects.get(name=k) # if already applied if applied_company in c: continue else: applied_company.students_applied.add(s) applied_company.save() #add this student to the list of applied_students #save # if unchecked.. then remove. for k in c: if k.name in request.POST.keys(): continue else: k.students_applied.remove(s) k.save() return our_redirect('/common/company/done')
def edit(request, prn): if "username" not in request.session: print "no session found" request.session['redirect'] = request.get_full_path() return our_redirect("/ldap_login") if prn != request.session['username']: print "prn", prn, type(prn) print "username", request.session['username'], type( request.session['username']) return HttpResponse('Please Edit ur own form :@') '''The problem with this view : We(I) are doing it the old-fashioned way. We(I) are not using the power of Models which allow automatic server-side validation -- i need to read on that. ''' #was prn passed and is it numeric really? if prn is not None and prn.isdigit() is True: #are we authorized to edit this ? #do we hv global edit privileges ? #kya ye hamara hi resume hai ? #do we hv the record ? s = student.objects.filter(pk=prn) #see the way to unzip a tuple that is returned by a func if len(s) is 0: return HttpResponse('This user doesnt exists') else: s = s[0] debugger("Resume found! Using it") #get all the records and tell us whether they were creatd or retrieved #have moved this to the student_info.models, because all Model info must come from there and tomo if we add a new model, we shouldn't have to come here to provide it's functionality. table = tables.get_tables(s) #get company specific required fields '''We are segregating the company Specific thigs into 3 sequences... a) the main table, which consists all rows of the main table structurw. Who are neither special kinds, nor are already filled. b) cs are the data filled by this partucular student. Main table fetches all the data to be collected per student. CS is the data ctually filled by the students. this is used to prefill the foem while editing.and the maintable is required for the "form" for a new user. ''' cs = companySpecificData.objects.filter( primary_table=s).order_by('valueOf') maintable = companySpecific.objects.exclude( fieldType='special').exclude( companyspecificdata__in=cs).order_by('displayText') print "CS ====", cs print "Maintable....", maintable table['mt'] = maintable table['cs'] = cs table['flag'] = 'edit' c = RequestContext(request, table) t = loader.get_template('student_info/form.html') return HttpResponse(t.render(c))
def ajaxRequest(request): '''for processing any ajax request for a field data''' '''will accept data in XML (ok?) and return data in XML ''' pass return our_redirect('/student_info/%d/edit' % (int(request.session['username']))) return HttpResponse( 'you arent supposed to see this page. if u see this please contact apoorva' )
def edit(request,prn): if "username" not in request.session: print "no session found" request.session['redirect'] = request.get_full_path(); return our_redirect("/ldap_login") if prn != request.session['username']: print "prn", prn, type(prn) print "username", request.session['username'],type(request.session['username']) return HttpResponse('Please Edit ur own form :@') '''The problem with this view : We(I) are doing it the old-fashioned way. We(I) are not using the power of Models which allow automatic server-side validation -- i need to read on that. ''' #was prn passed and is it numeric really? if prn is not None and prn.isdigit() is True: #are we authorized to edit this ? #do we hv global edit privileges ? #kya ye hamara hi resume hai ? #do we hv the record ? s = student.objects.filter(pk=prn); #see the way to unzip a tuple that is returned by a func if len(s) is 0: return HttpResponse('This user doesnt exists'); else: s=s[0] debugger("Resume found! Using it"); #get all the records and tell us whether they were creatd or retrieved #have moved this to the student_info.models, because all Model info must come from there and tomo if we add a new model, we shouldn't have to come here to provide it's functionality. table=tables.get_tables(s) #get company specific required fields '''We are segregating the company Specific thigs into 3 sequences... a) the main table, which consists all rows of the main table structurw. Who are neither special kinds, nor are already filled. b) cs are the data filled by this partucular student. Main table fetches all the data to be collected per student. CS is the data ctually filled by the students. this is used to prefill the foem while editing.and the maintable is required for the "form" for a new user. ''' cs=companySpecificData.objects.filter(primary_table=s).order_by('valueOf') maintable=companySpecific.objects.exclude(fieldType='special').exclude(companyspecificdata__in = cs).order_by('displayText'); print "CS ====",cs print "Maintable....",maintable table['mt']=maintable; table['cs']=cs; table['flag']='edit'; c = RequestContext(request,table); t = loader.get_template('student_info/form.html'); return HttpResponse(t.render(c));
def company_list(request): if 'username' not in request.session: request.session['redirect'] = request.get_full_path(); return our_redirect('/ldap_login/'); else: prn=request.session['username']; print prn try: s = student.objects.get(pk=prn) except Exception as e: output = "<h3>Fill in ur details first</h3>"; return HttpResponse(output); u=user.objects.get(pk=prn) companies=list(); for g in u.groups.all(): h=company.objects.filter(came_for_group=g) for c in h: if c not in companies: companies.extend(h) print "companies are ",companies today=datetime.today() main_list=list() for c in companies: c_dict=dict() print "processing Companies",c c_dict['name']=c.name; c_dict['date_of_applying']=c.last_date_of_applying c_dict['process']=c.date_of_process c_dict['info']=c.job_description; if c.last_date_of_applying > today: c_dict['gone']=""; else: c_dict['gone']="disabled=true"; m=c.students_applied.all() if s in m: c_dict['Checked']='Checked=true'; else: c_dict['Checked']=""; print "the dict", c_dict; main_list.append(c_dict) print main_list t=loader.get_template('company/company_names') c=RequestContext(request,{ 'companies':main_list, 'ROOT':ROOT }); return HttpResponse(t.render(c));
def admin_index(request): if 'username' not in request.session: return our_redirect('/ldap_login/') #g = group.objects.get(name='placement committee') if request.session['role'] != 'admin': return HttpResponse('page not for u') t = loader.get_template('company/admin_index.html') c = RequestContext(request, { 'ROOT': ROOT, 'MEDIA_URL': MEDIA_URL, }) return HttpResponse(t.render(c))
def company_list(request): if 'username' not in request.session: request.session['redirect'] = request.get_full_path() return our_redirect('/ldap_login/') else: prn = request.session['username'] print prn try: s = student.objects.get(pk=prn) except Exception as e: output = "<h3>Fill in ur details first</h3>" return HttpResponse(output) u = user.objects.get(pk=prn) companies = list() for g in u.groups.all(): h = company.objects.filter(came_for_group=g) for c in h: if c not in companies: companies.extend(h) print "companies are ", companies today = datetime.today() main_list = list() for c in companies: c_dict = dict() print "processing Companies", c c_dict['name'] = c.name c_dict['date_of_applying'] = c.last_date_of_applying c_dict['process'] = c.date_of_process c_dict['info'] = c.job_description if c.last_date_of_applying > today: c_dict['gone'] = "" else: c_dict['gone'] = "disabled=true" m = c.students_applied.all() if s in m: c_dict['Checked'] = 'Checked=true' else: c_dict['Checked'] = "" print "the dict", c_dict main_list.append(c_dict) print main_list t = loader.get_template('company/company_names') c = RequestContext(request, { 'companies': main_list, 'ROOT': ROOT }) return HttpResponse(t.render(c))
def admin_index(request): if 'username' not in request.session: return our_redirect('/ldap_login/') #g = group.objects.get(name='placement committee') if request.session['role'] != 'admin': return HttpResponse('page not for u'); t=loader.get_template('company/admin_index.html'); c=RequestContext(request,{ 'ROOT':ROOT, 'MEDIA_URL':MEDIA_URL, }) return HttpResponse(t.render(c))
def logged_in(request): #for now simply redirect to job posting page, as that is the only functionality offered '''print request.user print request t = loader.get_template('socialauth/index.html') c = RequestContext(request, { 'request':request } ) print request.user return HttpResponse(t.render(c));''' return our_redirect('/jobposting/add')
def logout(request): #are we actually logged in ? if 'username' in request.session: u = user.objects.get(username=request.session['username']) u.last_login = datetime.now() print u.last_login u.save() print 'logging you out' request.session.flush() else: #no, print 'redirecting to login page to tell you to login first :P' #then tell me to login first, using the message if possible #message = "Hey, you need to go in before you can go out :P :P"; return our_redirect('/login/')
def logout(request): #are we actually logged in ? if 'username' in request.session: u = user.objects.get(username = request.session['username']) u.last_login = datetime.now(); print u.last_login u.save(); print 'logging you out'; request.session.flush(); else: #no, print 'redirecting to login page to tell you to login first :P'; #then tell me to login first, using the message if possible #message = "Hey, you need to go in before you can go out :P :P"; return our_redirect('/login/');
def html(request,prn): if 'username' not in request.session: request.session['redirect'] = request.get_full_path(); return our_redirect('/login') '''if prn != request.session['username']: return HttpResponse('Not urs..!!')''' if prn is not None: try: s = student.objects.get(pk=prn); except: output = "<h3>Student details for PRN %s not found! <input type = 'button' value='Click to fill your details' onClick='%s/form'></h3>" % (prn,ROOT); return HttpResponse(output); data = tables.get_tables(s); t=loader.get_template('moderncv/htmlview.html') c=Context(data) return HttpResponse(t.render(c))
def fetch_index(request): if 'username' not in request.session: request.session['redirect'] = request.get_full_path() return our_redirect('/login') if request.session['role'] != 'admin': return HttpResponse('page not for u') com = company.objects.all() a = ['staff', 'placement committee'] g = group.objects.exclude(name__in=a) t = loader.get_template('company/fetch_students.html') full = get_full_list() c = RequestContext(request, { 'c': com, 'g': g, 'ROOT': ROOT, 'MEDIA_URL': MEDIA_URL, 'list': full }) return HttpResponse(t.render(c))
def fetch_index(request): if 'username' not in request.session: request.session['redirect'] = request.get_full_path(); return our_redirect('/login') if request.session['role'] !='admin': return HttpResponse('page not for u'); com=company.objects.all(); a = ['staff','placement committee'] g=group.objects.exclude(name__in = a); t=loader.get_template('company/fetch_students.html'); full = get_full_list(); c=RequestContext(request,{ 'c':com, 'g':g, 'ROOT':ROOT, 'MEDIA_URL':MEDIA_URL, 'list':full }) return HttpResponse(t.render(c))
def nayeforms(request,prn): #login checker if "username" not in request.session: print "No session found!" request.session['redirect'] = request.get_full_path(); return our_redirect("/login") elif prn != request.session['username']: print "prn", prn, type(prn) print "username", request.session['username'],type(request.session['username']) return HttpResponse('<b>Please edit your own form! :@</b>') from student_info.forms import PersonalForm,MarksForm,SwExposureForm,CertificationForm,WorkexForm,AcademicAchievementsForm, ProjectForm, ExtraCurricularForm, StudentForm, AdditionalInfoForm from student_info.models import student,personal,swExposure,marks,certification,workex,academic,project,extracurricular,AdditionalInfo,companySpecific, companySpecificData from django.forms.models import modelformset_factory print "Doing everything for prn", prn #for storing the data from the table data = {} #for storing the factories which generate our formsets formset_factories = {} #for storing the formsets themselves formsets = {} invalid_data = False s = None; try: s = student.objects.get(pk=prn) are_we_editing = True except: s = student.objects.create(pk=prn) are_we_editing = False; print "Are we editing", are_we_editing if request.method == 'POST': #the form was submitted print 'Processing form submission' #print "===POST===" #print request.POST try: student_data_valid = False other_data_valid = False #formset_factories -- kind of customized factories of forms for each of our models formset_factories['marks'] = modelformset_factory(marks,form=MarksForm,extra=0,can_delete=True) formset_factories['personal'] = modelformset_factory(personal,form=PersonalForm,extra=0) formset_factories['swExposure'] = modelformset_factory(swExposure, form=SwExposureForm, extra=0) formset_factories['certification'] = modelformset_factory(certification, form=CertificationForm, extra=0,can_delete=True) formset_factories['workex'] = modelformset_factory(workex, form=WorkexForm, extra=0,can_delete=True) formset_factories['academic'] = modelformset_factory(academic, form=AcademicAchievementsForm, extra=0,can_delete=True) formset_factories['project'] = modelformset_factory(project, form=ProjectForm, extra=0,can_delete=True) formset_factories['extracurricular'] = modelformset_factory(extracurricular, form=ExtraCurricularForm, extra=0,can_delete=True) formset_factories['additionalInfo'] = modelformset_factory(AdditionalInfo, form=AdditionalInfoForm, extra=0,can_delete=True) #generate a formset -- collection of forms for editing/creating new data formsets['marks'] = formset_factories['marks'](request.POST,prefix='marks') formsets['personal'] = formset_factories['personal'](request.POST,prefix='personal') formsets['swExposure'] = formset_factories['swExposure'](request.POST,prefix='swExposure') formsets['certification'] = formset_factories['certification'](request.POST,prefix='certification') formsets['workex'] = formset_factories['workex'](request.POST,prefix='workex') formsets['academic'] = formset_factories['academic'](request.POST,prefix='academic') formsets['project'] = formset_factories['project'](request.POST,prefix='project') formsets['extracurricular'] = formset_factories['extracurricular'](request.POST,prefix='extracurricular') formsets['additionalInfo'] = formset_factories['additionalInfo'](request.POST,prefix='additionalInfo') sf = StudentForm(request.POST,request.FILES,prefix='student',instance=s) print 'Starting to save data' print 'Processing Company Specific info' #WORST way of identifiying Company Specific fields for processing -- but can't find a better way, for now. for field,value in request.POST.lists(): field_name = field.split('_') print "Field ",field print "Value ",value if (field_name[0] == 'companySpecific'): try: print 'On',field, 'and Data',value cs = companySpecific.objects.get(key=field_name[1]) print "\n\n\nCOMPANY SPECIFIC...!!!!!!...", value, type(value); final_value = str(value[0]); for v in value[1:]: final_value += ',' + v csd, created_or_found = companySpecificData.objects.get_or_create(valueOf=cs,primary_table=s) csd.value = value csd.save() print 'Saving Company Specific Data' other_data_valid = True; except Exception as e: print "===================" print "Error with Company data :", print e other_data_valid = False; #Add the error message to be displayed in the template messages.error(request, "<b>Company Specific Info :</b> %s" % e) #raise exception so that we can go back to displaying the form raise Exception; print 'Processing student data', student_data_valid = sf.is_valid() if student_data_valid: print 'Saved all submitted data for Student Basic info' sf.save() else: print "===================" print "Error with Student data :", print sf.errors; #Add the error message to be displayed in the template messages.error(request, "<b>Basic Information: </b>%s" % sf.errors); #raise exception so that we can go back to displaying the form raise Exception; print 'Student data validity status : %s' % student_data_valid for f in formsets: #formsets[f].clean() print 'Processing ',f other_data_valid = formsets[f].is_valid() if other_data_valid: instances = formsets[f].save(commit=False) for i in instances: i.primary_table = s i.save() print 'Saved all submitted data for ',f else: #Error!! print "===================" print "Error with %s is :" % (f) print formsets[f].errors; print 'Other data validity status is : %s' % other_data_valid #Add the error message to be displayed in the template messages.error(request, "<b>%s :</b> %s " % (f.title(),formsets[f].errors)); #raise exception so that we can go back to displaying the form raise Exception; except: if (not student_data_valid) and (not are_we_editing): #we were trying to save a NEW student's data and encountered problem print 'Student data is invalid and we are creating new record', s.delete() elif (not student_data_valid) and (are_we_editing): #we were trying to save a OLD student's data and encountered errors print 'Student data is invalid and we are editing', pass #the data wasn't actually saved because of django's mechanisms elif (not other_data_valid) and (not are_we_editing): print "Figure out what to do in case tehre are errors in saving NEW data for a student in various models" pass elif (not other_data_valid) and (are_we_editing): print 'Other data is invalid and we are editing existing details' pass #the data wasn't actually saved because of django's mechanisms if student_data_valid and other_data_valid: return our_redirect('/common/Submitted/done'); else: #Company Specific fields -- special thingys ;) #These provide dynamic fields in the form which can be added in the form by the placement team. #existing data for company specific fields data['companySpecificData'] = companySpecificData.objects.filter(primary_table=s).order_by('valueOf') already_filled_list = data['companySpecificData'].values_list('valueOf') #provide for new fields to be displayed to user #here we select only those fields which haven't been filled by the user as obtained in the above list. #basically this is a query which says --> #"Give me all Company Specific fields excluding those whose values have been filled by the user and order them by their displayText" data['companySpecificFields'] = companySpecific.objects.all().exclude(fieldType='special').exclude(id__in=already_filled_list).order_by('displayText') print "Invalid data! Returning form for editing"; else: #new form is being displayed print 'Displaying new/edit form' data['marks'] = marks.objects.filter(primary_table=prn) if data['marks'].count() == 0: #no existing data for this student print "No existing marks data found for this student" formset_factories['marks'] = modelformset_factory(marks,form=MarksForm,exclude=('primary_table'),extra=3, can_delete=True) formsets['marks'] = formset_factories['marks'](prefix='marks',queryset = data['marks']) else: formset_factories['marks'] = modelformset_factory(marks,form=MarksForm,extra=0,can_delete=True) formsets['marks'] = formset_factories['marks'](prefix='marks',queryset = data['marks']) data['personal'] = personal.objects.filter(primary_table=prn) if data['personal'].count() == 0: print "No existing personal data found for this student" formset_factories['personal'] = modelformset_factory(personal,form=PersonalForm,extra=1) formsets['personal'] = formset_factories['personal'](prefix='personal',queryset = data['personal']) else: formset_factories['personal'] = modelformset_factory(personal,form=PersonalForm,extra=0) formsets['personal'] = formset_factories['personal'](prefix='personal',queryset = data['personal']) data['swExposure'] = swExposure.objects.filter(primary_table=prn) if data['swExposure'].count() == 0: print "No existing software exposure data found for this student" formset_factories['swExposure'] = modelformset_factory(swExposure,form=SwExposureForm,extra=1) formsets['swExposure'] = formset_factories['swExposure'](prefix='swExposure',queryset = data['swExposure']) else: formset_factories['swExposure'] = modelformset_factory(swExposure,form=SwExposureForm,extra=0) formsets['swExposure'] = formset_factories['swExposure'](prefix='swExposure',queryset = data['swExposure']) data['certification'] = certification.objects.filter(primary_table=prn) if data['certification'].count() == 0: print "No existing certification data found for this student" formset_factories['certification'] = modelformset_factory(certification,form=CertificationForm,extra=1,can_delete=True) formsets['certification'] = formset_factories['certification'](prefix='certification',queryset=data['certification']) else: formset_factories['certification'] = modelformset_factory(certification,form=CertificationForm,extra=0,can_delete=True) formsets['certification'] = formset_factories['certification'](prefix='certification',queryset = data['certification']) data['workex'] = workex.objects.filter(primary_table=prn) if data['workex'].count() == 0: print "No existing workex data found for this student" formset_factories['workex'] = modelformset_factory(workex, form=WorkexForm, extra=1,can_delete=True) formsets['workex'] = formset_factories['workex'](prefix='workex',queryset=data['workex']) else: formset_factories['workex'] = modelformset_factory(workex, form=WorkexForm, extra=0,can_delete=True) formsets['workex'] = formset_factories['workex'](prefix='workex',queryset = data['workex']) data['academic'] = academic.objects.filter(primary_table=prn) if data['academic'].count() == 0: print "No existing academic data found for this student" formset_factories['academic'] = modelformset_factory(academic, form=AcademicAchievementsForm, extra=1,can_delete=True) formsets['academic'] = formset_factories['academic'](prefix='academic',queryset=data['academic']) else: #existing data was found for this student formset_factories['academic'] = modelformset_factory(academic, form=AcademicAchievementsForm, extra=0,can_delete=True) formsets['academic'] = formset_factories['academic'](prefix='academic',queryset=data['academic']) data['project'] = project.objects.filter(primary_table=prn) if data['project'].count() == 0: print "No existing project data found for this student" formset_factories['project'] = modelformset_factory(project, form=ProjectForm, extra=1,can_delete=True) formsets['project'] = formset_factories['project'](prefix='project',queryset=data['project']) else: #existing data was found for this student formset_factories['project'] = modelformset_factory(project, form=ProjectForm, extra=0,can_delete=True) formsets['project'] = formset_factories['project'](prefix='project',queryset=data['project']) data['extracurricular'] = extracurricular.objects.filter(primary_table=prn) if data['extracurricular'].count() == 0: print "No existing extracurricular data found for this student" formset_factories['extracurricular'] = modelformset_factory(extracurricular, form=ExtraCurricularForm, extra=1,can_delete=True) formsets['extracurricular'] = formset_factories['extracurricular'](prefix='extracurricular',queryset=data['extracurricular']) else: #existing data was found for this student formset_factories['extracurricular'] = modelformset_factory(extracurricular, form=ExtraCurricularForm, extra=0,can_delete=True) formsets['extracurricular'] = formset_factories['extracurricular'](prefix='extracurricular',queryset=data['extracurricular']) data['additionalInfo'] = AdditionalInfo.objects.filter(primary_table=prn) if data['additionalInfo'].count() == 0: print "No existing additionalInfo data found for this student" formset_factories['additionalInfo'] = modelformset_factory(AdditionalInfo, form=AdditionalInfoForm, extra=1,can_delete=True) formsets['additionalInfo'] = formset_factories['additionalInfo'](prefix='additionalInfo',queryset=data['additionalInfo']) else: #existing data was found for this student formset_factories['additionalInfo'] = modelformset_factory(AdditionalInfo, form=AdditionalInfoForm, extra=0,can_delete=True) formsets['additionalInfo'] = formset_factories['additionalInfo'](prefix='additionalInfo',queryset=data['additionalInfo']) #Company Specific fields -- special thingys ;) #These provide dynamic fields in the form which can be added in the form by the placement team. #existing data for company specific fields data['companySpecificData'] = companySpecificData.objects.filter(primary_table=s).order_by('valueOf') already_filled_list = data['companySpecificData'].values_list('valueOf') #provide for new fields to be displayed to user #here we select only those fields which haven't been filled by the user as obtained in the above list. #basically this is a query which says --> #"Give me all Company Specific fields excluding those whose values have been filled by the user and order them by their displayText" data['companySpecificFields'] = companySpecific.objects.all().exclude(fieldType='special').exclude(id__in=already_filled_list).order_by('displayText') #Student Data data['student'] = s sf = StudentForm(prefix='student',instance=data['student']) t = loader.get_template('student_info/nayeforms.html') context = { 'prn' : prn, 'marks_formset' : formsets['marks'], 'personal_formset' : formsets['personal'], 'swExposure_formset' : formsets['swExposure'], 'certification_formset' : formsets['certification'], 'workex_formset': formsets['workex'], 'academic_formset' : formsets['academic'], 'project_formset' : formsets['project'], 'extracurricular_formset' : formsets['extracurricular'], 'additionalInfo_formset':formsets['additionalInfo'], 'student_form' : sf, 's' : s, #student object 'ROOT' : ROOT, 'companySpecificData': data['companySpecificData'], 'companySpecificFields': data['companySpecificFields'], } c = RequestContext(request,context) return HttpResponse(t.render(c))
def submit(request, prn): '''processes submissions of NEW forms and also EDIT forms!''' if 'username' not in request.session: print "no session found" request.session['redirect'] = request.get_full_path() return our_redirect('/ldap_login') #was javascript enabled and everything ok on the client side ??? if not ('allok' in request.POST and request.POST['allok'] == '1'): return HttpResponse( "<h2 align='center' style='color: red;'> Hey, This is Server, you need to enable JavaScript if you want us to help you! </h2>" ) #what is submitted ? print "I have got files called ", request.FILES photo_file = RESUME_STORE + "/photos/" + prn + ".png" if path.exists(photo_file): photo_exists = True print "Photo already existed" else: photo_exists = False print "Photo doesn't exist already" if len(request.FILES) is 0: print "No photo was submitted!" else: print "A photo was submitted!" #let's make photo file non-mandatory. #if not photo_exists and len(request.FILES) is 0: # return our_redirect('/form') #TODO: check whether the photo is a photo or something else ? for f in request.FILES.values(): dest = RESUME_STORE + "/photos/" + prn + ".png" #so that things remain soft-coded :P print "files to be saved in", dest destination = open(dest, 'wb+') print "i got the file handle as ", destination for chunk in f.chunks(): destination.write(chunk) destination.close() post = request.POST print "========>>>POST<<<========" for p, v in post.lists(): print p, "..........", v # pprint(post); # check for the validity of the prn etc... s = student.objects.filter(pk=prn) print s, len(s) if len(s) is 1: print " ======>>> editing original <<<=======" s[0].delete() #delete to create a new one. try: s = student.objects.create( pk=prn, fullname=post['fullname'], career_objective=post['career_objective'], ) s.save() #will also update the timestamp; p = personal.objects.get_or_create(primary_table=s)[0] table_dict = dict() mvsd = dict() extra_fields = dict() l = [ 'marks', 'extracurricular', 'academic', 'certification', 'project', 'workex', 'ExtraField' ] #list of model names other than personal. for field, data in post.lists(): #it will be a list #we are using this long branch of IF and ELIFs because Python doesn't have switch case!!! if field == 'csrfmiddlewaretoken': continue field_name = field.split('_') print "type(field)", type(field), field if len(field_name) is 1: # for student model #print "=====>Setting ", field_name[0] , "of student with ",data[0] s.__setattr__(field_name[0], data[0]) continue if field_name[0] == 'personal': if field_name[2].isdigit() is False: index = field_name[1] + '_' + field_name[2] #print "=====> adding", data , "to attribute", index, "of Personal"; p.__setattr__(index, data[0]) if field_name[0] == "birthdate" and field_name[1] == 'monthyear': date = data[0].split(',') print "=====>DATE<=====", date print datetime(int(date[2]), int(date[1]), int(date[0])) p.__setattr__( "birthdate", datetime(int(date[2]), int(date[1]), int(date[0]))) #if it's an ExtraField '''elif 'ExtraField' in field_name[0]: print "found ExtraFile" field_name=field.split('_'); column_dict=dict(); column_dict[field_name[1]]=data; index=field_name[0]+'_'+field_name[2]; if field_name[0].lstrip('ExtraField') == '': continue if index not in table_dict: i='ExtraField_title_'+field_name[0].lstrip('ExtraField'); table_dict[index]={'title':post[i]} table_dict[index].update(column_dict);''' if (field_name[0] == 'companySpecific'): try: cs = companySpecific.objects.get(key=field_name[1]) print "\n\nCOMPANY SPECIFIC....!!!!!!...." #print "\n\n\nCOMPANY SPECIFIC...!!!!!!...", data, type(data); a = str(data[0]) for d in data[1:]: a += ',' + d csd = companySpecificData(primary_table=s, valueOf=cs, value=a) csd.save() except: pass if str(field_name[0]) in l: column_dict = dict() column_dict[field_name[1]] = data[0] if "title" not in column_dict: if field_name[0] == "ExtraField": column_dict['title'] = post.get( 'ExtraField_title_1', '' ) #if it's not found return a default value -- because it was raising exceptions...done using django-docs/ref/request-response.html#querydict-objects else: column_dict['title'] = field_name[0] index = field_name[0] + '_' + field_name[2] if index not in table_dict: table_dict[index] = dict() table_dict[index].update(column_dict) '''row = eval("%s" % field_name[0]).objects.get_or_create(primary_table=s); row[field_name[1]] = data;''' if len(field_name) is 3 and field_name[ 0] not in l: # for multi-valued single Display print "!!!!!!!!inside mvsd processing" if field_name[2].isdigit() is False: field_name[1] = field_name[1] + '_' + field_name[2] else: index = field_name[0] + '_' + field_name[1] if index not in mvsd: mvsd[index] = data[0] else: mvsd[index] += ',' + data[0] #if we are retrieving the data '''row = eval("%s" % field_name[0]).objects.get_or_create(primary_table=prn); row[field_name[1]] = data; row.save();''' p.save() print "P saved" print "=========>>>> The Main list : <==============" pprint(table_dict) #print "======> s/w Exposure=====" #print sw_exposure print "=====>MVSD<======" print mvsd except Exception as e: print "======EXCEPTION....while submitting============", e, print print "=====Traceback=====" #exception_info = exc_info(); #traceback.print_tb(exception_info[2]); return our_redirect('/form') # ============>>> MVSD <<<==================== for table_row, value in mvsd.iteritems(): if table_row.startswith('Extra'): continue print "FO" tablerow = table_row.split('_') if tablerow[0] == "personal": table = p else: table = eval(tablerow[0]).objects.get_or_create(primary_table=s) table = table[0] print "table-->", table print "we have a column called __%s__" % (tablerow[1]) print "value--> Can't be printed here you stiupid!" #print "value--->",value; table.__setattr__(tablerow[1], value) table.save() #print "table value====>>>", table.__getattribute__(tablerow[1]) #print table,".",tablerow[1]," value set to ", table.__getattribute__(tablerow[1]); #===========>>> Table Dict <<<================= for table, row_values in table_dict.iteritems(): r = table.split('_') print "=======> table ", r[0] t = eval(r[0])() t.primary_table = s print "Creating new row for ", r[0] if "desc" in row_values and row_values["desc"] == "": print "======>>FALTU FIELD<<======" # for field that just comes in the POST.. will need to fix in the form later. continue s.__setattr__(r[0], True) for c, d in row_values.iteritems(): if "monthyear" in c: date = d.split(',') d = datetime(int(date[2]), int(date[1]), int(date[0])) if "end" in c: c = "endDate" else: c = "fromDate" t.__setattr__(c, d) #UNCOMENT BELOW ONLY IN DEV ENVIRONMENT NOT PRODUCTION - YOU HAVE BEEN WARNED #print r[0],".",c,"======>",d; t.save() print "Saved" s.save() print "S,saved" p.save() print "P saved" return our_redirect('/common/Submitted/done')
def login(request): #are we processing login attempt ? message = None #print request.POST if 'username' in request.session: if 'redirect' in request.session and request.session['redirect'].strip( ) != '': a = request.session['redirect'] request.session['redirect'] = '' return our_redirect(a) else: return our_redirect('/home') if 'username' in request.POST: # and 'password' in request.POST: print "== Got username..!!!!" if request.POST['username'] == "": print "but its empty" status = False message = "please enter Username" else: print "its Not empty...its", request.POST['username'] print 'processing login attempt' try: #comment this line when you ARE OUTSIDE SICSR! status = False ldap = '' if ROOT.strip() != "": status = ldap_authenticate(request.POST['username'], request.POST['password']) ldap = True print "tried ldap" if ldap is not True or status is not True: # if ldap is false, then dont check status as this is primary mode of auth. if ldap is true, then do this only when status is false. print "authenticating via django auth" USER = authenticate(username=request.POST['username'], password=request.POST['password']) if USER is not None: print "django login suucess" #request.session['last_login'] = USER.last_login; #login(request,USER); print "Admin user found, its groups are", user.groups #ldap = False if USER.is_staff: request.session['role'] = 'admin' status = True else: print "django login false" status = False if ROOT == '': status = True #UNCOMMENT the next line when you are outside SICSR! #status = True; print ldap print status print 'auth process completed' except Exception as e: return HttpResponse('Error!!! %s' % e) if status: #if successful ldap login #update last_login timestamp #store encrypted password #start session request.session.set_expiry(7200) request.session['username'] = request.POST['username'] userName = request.session['username'] #check for user existance... and/or add the use in our feedback database..!! userexists = user.objects.get_or_create(pk=userName) if not userexists[1]: request.session['last_login'] = userexists[0].last_login else: request.session['last_login'] = datetime.now() print request.session['last_login'] userexists[0].last_login = datetime.now() + timedelta(minutes=30) userexists[0].save() # this auto gruop assignment takes place by the logic that all students log in from thier PRN's and thier 1st 8 digit of thier PRN represents thier gruop.. to assignm a student to another group we need to do it manually..:) and we need to find out a better way of creating groups..!!! :D # to check whether its a student or staff.. :) if userName.isdigit() is True: print "its a student" groupid = userName[0:8] request.session['role'] = 'student' else: from django.contrib.auth.models import User, Group try: print userName u_admin = User.objects.get(username=userName) g_admin = Group.objects.get(name='placement committee') print "USER == ", u_admin, "GROIUP==", g_admin if g_admin in u_admin.groups.all(): print "admin found" PC_group = group.objects.get_or_create( name='placement committee')[0] PC_group.save() userexists[0].groups.add(PC_group) userexists[0].save() except: print "its a staff..!" groupid = 'staff' print "putting him in group", group groupexists = group.objects.get_or_create(name=groupid)[0] groupexists.save() print "groupexists... = ", groupexists userexists[0].groups.add(groupexists) userexists[0].save() #our_redirect to the index view! if 'redirect' in request.session: a = request.session['redirect'] request.session['redirect'] = '' return our_redirect('/' + a.strip(ROOT)) else: return our_redirect('/home') else: # if status == False message = 'Wrong Username/Password' print "because status was", status, "hence message is", message print 'redirecting now...' else: # when we first enter...... # print request.POST['username'] # print request.POST['password'] print "nothing is true hence showing the login teplate again" #we aren't either procesing a login attempt OR the user had a failed login attempt! #unsuccessful ldap login #wrong username/password!!! return our_redirect('/home')
def passwordHelp(request): if 'username' in request.session: return our_redirect('/home') else: return render_to_response('ldap_login/passwordhelp.html')
def submit(request, prn): '''processes submissions of NEW forms and also EDIT forms!''' if 'username' not in request.session: print "no session found" request.session['redirect'] = request.get_full_path(); return our_redirect('/ldap_login') #was javascript enabled and everything ok on the client side ??? if not ('allok' in request.POST and request.POST['allok'] == '1'): return HttpResponse("<h2 align='center' style='color: red;'> Hey, This is Server, you need to enable JavaScript if you want us to help you! </h2>"); #what is submitted ? print "I have got files called ", request.FILES; photo_file=RESUME_STORE+"/photos/"+prn+".png"; if path.exists(photo_file): photo_exists = True; print "Photo already existed"; else: photo_exists = False; print "Photo doesn't exist already"; if len(request.FILES) is 0: print "No photo was submitted!"; else: print "A photo was submitted!"; #let's make photo file non-mandatory. #if not photo_exists and len(request.FILES) is 0: # return our_redirect('/form') #TODO: check whether the photo is a photo or something else ? for f in request.FILES.values(): dest=RESUME_STORE+"/photos/"+prn+".png" #so that things remain soft-coded :P print "files to be saved in", dest; destination = open(dest, 'wb+') print "i got the file handle as ",destination for chunk in f.chunks(): destination.write(chunk) destination.close() post=request.POST; print "========>>>POST<<<========" for p,v in post.lists(): print p,"..........",v # pprint(post); # check for the validity of the prn etc... s=student.objects.filter(pk=prn) print s, len(s) if len(s) is 1: print " ======>>> editing original <<<=======" s[0].delete() #delete to create a new one. try: s = student.objects.create( pk=prn, fullname=post['fullname'], career_objective=post['career_objective'], ) s.save(); #will also update the timestamp; p = personal.objects.get_or_create(primary_table=s)[0]; table_dict=dict(); mvsd=dict(); extra_fields = dict() l = ['marks', 'extracurricular','academic','certification','project','workex','ExtraField'] #list of model names other than personal. for field,data in post.lists(): #it will be a list #we are using this long branch of IF and ELIFs because Python doesn't have switch case!!! if field == 'csrfmiddlewaretoken': continue; field_name=field.split('_'); print "type(field)", type(field), field if len(field_name) is 1: # for student model #print "=====>Setting ", field_name[0] , "of student with ",data[0] s.__setattr__(field_name[0],data[0]) continue; if field_name[0] == 'personal': if field_name[2].isdigit() is False: index=field_name[1]+'_'+field_name[2]; #print "=====> adding", data , "to attribute", index, "of Personal"; p.__setattr__(index,data[0]); if field_name[0]=="birthdate" and field_name[1] == 'monthyear': date=data[0].split(',') print "=====>DATE<=====",date print datetime(int(date[2]),int(date[1]),int(date[0])) p.__setattr__("birthdate",datetime(int(date[2]),int(date[1]),int(date[0]))); #if it's an ExtraField '''elif 'ExtraField' in field_name[0]: print "found ExtraFile" field_name=field.split('_'); column_dict=dict(); column_dict[field_name[1]]=data; index=field_name[0]+'_'+field_name[2]; if field_name[0].lstrip('ExtraField') == '': continue if index not in table_dict: i='ExtraField_title_'+field_name[0].lstrip('ExtraField'); table_dict[index]={'title':post[i]} table_dict[index].update(column_dict);''' if (field_name[0] == 'companySpecific'): try: cs=companySpecific.objects.get(key=field_name[1]) print "\n\nCOMPANY SPECIFIC....!!!!!!...." #print "\n\n\nCOMPANY SPECIFIC...!!!!!!...", data, type(data); a = str(data[0]); for d in data[1:]: a += ',' + d csd=companySpecificData( primary_table=s, valueOf=cs, value=a ); csd.save(); except: pass; if str(field_name[0]) in l: column_dict=dict(); column_dict[field_name[1]]=data[0]; if "title" not in column_dict: if field_name[0]=="ExtraField": column_dict['title']=post.get('ExtraField_title_1','') #if it's not found return a default value -- because it was raising exceptions...done using django-docs/ref/request-response.html#querydict-objects else: column_dict['title']=field_name[0] index=field_name[0]+'_'+field_name[2]; if index not in table_dict: table_dict[index]=dict() table_dict[index].update(column_dict) '''row = eval("%s" % field_name[0]).objects.get_or_create(primary_table=s); row[field_name[1]] = data;''' if len(field_name) is 3 and field_name[0] not in l: # for multi-valued single Display print "!!!!!!!!inside mvsd processing"; if field_name[2].isdigit() is False: field_name[1]=field_name[1]+'_'+field_name[2] else: index=field_name[0]+'_'+field_name[1]; if index not in mvsd: mvsd[index]=data[0]; else: mvsd[index]+=','+data[0]; #if we are retrieving the data '''row = eval("%s" % field_name[0]).objects.get_or_create(primary_table=prn); row[field_name[1]] = data; row.save();''' p.save(); print "P saved" print "=========>>>> The Main list : <==============" pprint(table_dict) #print "======> s/w Exposure=====" #print sw_exposure print "=====>MVSD<======" print mvsd except Exception as e: print "======EXCEPTION....while submitting============", e,; print print "=====Traceback=====" #exception_info = exc_info(); #traceback.print_tb(exception_info[2]); return our_redirect('/form') # ============>>> MVSD <<<==================== for table_row, value in mvsd.iteritems(): if table_row.startswith('Extra'): continue; print "FO" tablerow=table_row.split('_'); if tablerow[0] == "personal": table=p; else: table=eval(tablerow[0]).objects.get_or_create(primary_table=s); table=table[0]; print "table-->",table; print "we have a column called __%s__" % (tablerow[1]); print "value--> Can't be printed here you stiupid!" #print "value--->",value; table.__setattr__(tablerow[1], value); table.save(); #print "table value====>>>", table.__getattribute__(tablerow[1]) #print table,".",tablerow[1]," value set to ", table.__getattribute__(tablerow[1]); #===========>>> Table Dict <<<================= for table, row_values in table_dict.iteritems(): r=table.split('_') print "=======> table ", r[0]; t=eval(r[0])(); t.primary_table=s print "Creating new row for ", r[0]; if "desc" in row_values and row_values["desc"] == "": print "======>>FALTU FIELD<<======" # for field that just comes in the POST.. will need to fix in the form later. continue; s.__setattr__(r[0],True); for c,d in row_values.iteritems(): if "monthyear" in c: date=d.split(','); d=datetime(int(date[2]), int(date[1]), int(date[0])) if "end" in c: c="endDate" else: c="fromDate" t.__setattr__(c,d); #UNCOMENT BELOW ONLY IN DEV ENVIRONMENT NOT PRODUCTION - YOU HAVE BEEN WARNED #print r[0],".",c,"======>",d; t.save(); print "Saved" s.save(); print "S,saved" p.save(); print "P saved" return our_redirect('/common/Submitted/done');
def got_placed(request): if 'username' not in request.session: request.session['redirect'] = request.get_full_path(); return our_redirect('/ldap_login/') #if 'POST' not in request: # print 'no post' count = student.objects.all().count(); try: placed_id = request.POST['what'] filter = request.POST['filter'] except KeyError: #return HttpResponse('PLease fill all fields') return render_to_response('admin/reportsmenu.html', {'ROOT':ROOT},context_instance = RequestContext(request)) def mkdict(stu,type): lala = [] for items in stu: toreturn = {} toreturn['other'] = items; if type == 0: # items[0].__class__.__name__ = 'student' toreturn['company'] = items.company; u = user.objects.get(username = items.student.prn); else: print items u = user.objects.get(username = items.prn) toreturn['group'] = u.groups.all()[0] lala.append(toreturn) return lala #g = group.objects.get(name='placement committee') #there might be a case when there would be no role in the session!! -- though we need to correct and avoid such a case actually! if (not request.session.has_key('role')) or (request.session['role'] != 'admin'): return HttpResponse('not for u'); placed_stu=placement_in.objects.all(); from operator import itemgetter; a = lambda(x): itemgetter(filter)(x).__str__() if placed_id == 'placed': label = ['placed','unplaced'] context = {'placed':'yes','PS':sorted(mkdict(placed_stu,0),key = a)}; elif placed_id == 'unplaced': slist=[] label = ['unplaced','placed'] for p in placed_stu: slist.append(p.student.prn) unplaced_stu=student.objects.exclude(prn__in=slist); context = {'placed':'no','UPS':sorted(mkdict(unplaced_stu,1),key = a)}; try: leng = len(context['UPS']) print context['UPS'] except: leng = len(context['PS']) print context['PS'] context['count']=count; context['fil'] = filter; #because flter is a keyword i think context['ROOT'] = ROOT c = Context(context); t=loader.get_template('company/got_placed.html'); print "=========",request.get_full_path() return HttpResponse(t.render(c))
def login(request): #are we processing login attempt ? message = None; #print request.POST if 'username' in request.session: if 'redirect' in request.session and request.session['redirect'].strip() != '': a = request.session['redirect'] request.session['redirect'] = '' return our_redirect(a); else: return our_redirect('/home'); if 'username' in request.POST:# and 'password' in request.POST: print "== Got username..!!!!" if request.POST['username'] == "": print"but its empty" status=False; message="please enter Username" else: print "its Not empty...its",request.POST['username'] print 'processing login attempt'; try: #comment this line when you ARE OUTSIDE SICSR! status = False ldap = ''; if ROOT.strip() != "": status = ldap_authenticate(request.POST['username'],request.POST['password']); ldap = True print "tried ldap" if ldap is not True or status is not True: # if ldap is false, then dont check status as this is primary mode of auth. if ldap is true, then do this only when status is false. print "authenticating via django auth" USER = authenticate(username = request.POST['username'], password = request.POST['password']) if USER is not None: print "django login suucess" #request.session['last_login'] = USER.last_login; #login(request,USER); print "Admin user found, its groups are", user.groups; #ldap = False if USER.is_staff: request.session['role'] = 'admin' status = True; else: print "django login false" status = False; if ROOT == '': status = True #UNCOMMENT the next line when you are outside SICSR! #status = True; print ldap print status; print 'auth process completed' except Exception as e: return HttpResponse('Error!!! %s' % e); if status: #if successful ldap login #update last_login timestamp #store encrypted password #start session request.session.set_expiry(7200); request.session['username'] = request.POST['username']; userName=request.session['username'] #check for user existance... and/or add the use in our feedback database..!! userexists=user.objects.get_or_create(pk=userName) if not userexists[1]: request.session['last_login'] = userexists[0].last_login; else: request.session['last_login']=datetime.now(); print request.session['last_login'] userexists[0].last_login = datetime.now() + timedelta(minutes = 30); userexists[0].save(); # this auto gruop assignment takes place by the logic that all students log in from thier PRN's and thier 1st 8 digit of thier PRN represents thier gruop.. to assignm a student to another group we need to do it manually..:) and we need to find out a better way of creating groups..!!! :D # to check whether its a student or staff.. :) if userName.isdigit() is True: print "its a student" groupid=userName[0:8]; request.session['role'] = 'student' else: from django.contrib.auth.models import User, Group; try: print userName u_admin = User.objects.get(username = userName) g_admin = Group.objects.get(name = 'placement committee') print "USER == ",u_admin, "GROIUP==", g_admin; if g_admin in u_admin.groups.all(): print "admin found"; PC_group = group.objects.get_or_create(name= 'placement committee')[0] PC_group.save(); userexists[0].groups.add(PC_group); userexists[0].save(); except: print "its a staff..!" groupid='staff' print "putting him in group", group; groupexists=group.objects.get_or_create(name=groupid)[0] groupexists.save(); print "groupexists... = ", groupexists userexists[0].groups.add(groupexists); userexists[0].save(); #our_redirect to the index view! if 'redirect' in request.session: a = request.session['redirect'] request.session['redirect'] ='' return our_redirect('/'+a.strip(ROOT)); else: return our_redirect('/home'); else: # if status == False message = 'Wrong Username/Password'; print "because status was", status, "hence message is", message; print 'redirecting now...'; else: # when we first enter...... # print request.POST['username'] # print request.POST['password'] print "nothing is true hence showing the login teplate again" #we aren't either procesing a login attempt OR the user had a failed login attempt! #unsuccessful ldap login #wrong username/password!!! return our_redirect('/home');
def pdf(request,prn): if 'username' not in request.session: request.session['redirect'] = request.get_full_path(); return our_redirect('/ldap_login/') if prn != request.session['username']: return HttpResponse('Not your resume!') if prn is not None: try: s = student.objects.get(pk=str(prn)); print "We have got a student ",s try: r = resume.objects.get(prn=s); except Exception as e: #no resume was ever created for this user, hence we need to generate atleast latex once. print "====pdf==== Resume record doesn't exist...calling latex()"; latex(request,prn); finally: r = resume.objects.get(prn=s); print "======pdf======= Ok, now we have ",r except Exception as e: output = "<h3>Student details for PRN %s not found! Can't generate a PDF!</h3>" % (prn); print "=======pdf ========", e; return HttpResponse(output); print "Last TEX generated ", r.last_tex_generated; print "Last PDF generated ", r.last_pdf_generated; #compare generate_resume.models.resume.last_tex_generated with student_info.models.student_last_updated and decide! tex_file = "%s/%s/%s.tex" % (RESUME_STORE,prn,prn); #do we have a fresher .TEX file compared to the infromation filled by the student ? if (r.last_tex_generated is not None) and (r.last_tex_generated < s.last_update) or (not(path.exists(tex_file))): #oh no! it isn't fresher! generate it again! print "we have got a stale .TEX file! regenerating it by calling latex" latex(request,prn); else: #ok, there is no need to regenerate latex pass; #Now...is the pdf file fresher ? pdf_file = "%s/%s/%s.pdf" % (RESUME_STORE, prn, prn); if (r.last_pdf_generated is not None) and (r.last_pdf_generated > r.last_tex_generated) and (path.exists(pdf_file)): #the pdf file is fresher, so we don't need to regenerate it! let's just give it back. print "PDF file for %s is already fresher, so giving it back directly!" % (r.prn); else: print "PDF file is stale!"; #the pdf file is stale, get a fresh copy! #generate it's pdf pdf_file = "/tmp/%s.pdf" % (prn); return_status = False; #find the tex file try: #generate the pdf copy_photo_command = "cp -v %s/photos/%s.* %s/%s/" % (RESUME_STORE,prn,RESUME_STORE,prn); get_done(copy_photo_command); pdf_generation_command = "pdflatex --interaction=nonstopmode -etex -output-directory=/tmp %s/%s/%s.tex" % (RESUME_STORE,prn,prn); for i in range(0,3): #run the pdflatex command min 2 and max 3 times -- Manjusha Mam, Bhaskaracharya Pratishthana print "===========>PASS %d<===========" % (i); return_status = get_done(pdf_generation_command) #print "Return status is ",return_status; #doesn't matter now...after get done. pdf_file = "/tmp/%s.pdf" % prn; copy_pdf_command = "cp -v /tmp/%s.pdf %s/%s/" % (prn, RESUME_STORE,prn); #copy the .pdf to the user's directory in STORE so that we can reuse it get_done(copy_pdf_command); print "Updating timestamp for the PDF generation in our records" r.last_pdf_generated = datetime.now(); r.save(); except Exception as e: response = HttpResponse("Some problem!"); print 'Exception was ', e; #open the generated pdf file resume_pdf = open(pdf_file); #prepare the file to be sent response = HttpResponse(resume_pdf.read(), mimetype="application/pdf"); resume_pdf.close(); #name the file properly response['Content-Disposition'] = "attachment; filename=SICSR_%s_resume.pdf" % s.fullname; else: output = "<h3>Hey, pass me a PRN man!</h3>"; response = HttpResponse(output); return response;
def latex(request,prn): if 'username' not in request.session: request.session['redirect'] = request.get_full_path(); return our_redirect('/ldap_login/') '''generates the resume and puts it into the resume store for version control''' #the current user from session; if prn != request.session['username']: return HttpResponse('Please mind your own resume...') if prn is not None: try: s = student.objects.get(pk=str(prn)) print "=============== inside Latex.. found S .....",s except Exception as e: print "======inside latex... exception",e output = "<h3>Student details for PRN %s not found! Can't generate a LaTeX file!</h3>" % (prn); return HttpResponse(output); if s is not None: print "===latex=== is not NOne" #pass the student object with all his entered info to the template generator t = loader.get_template('%s/template.tex' % RESUME_FORMAT); print "=====latex ===t ",t #add the basic info wala original object also student_data=tables.get_tables(s) #student_data['photo'] = RESUME_STORE + "photos/" + prn + ".png" student_data['photo'] = "%s.png" % (prn); pprint(student_data); c = Context(student_data); try: print " =latex==== inside the try" #every latex file goes into that prn's directory destination_dir = '%s/%s/' % (RESUME_STORE, prn) try: chdir(destination_dir) #if we can't change into it, create it! except OSError: print "===latex === Os Error aya tha.. making dIr" mkdir(destination_dir); finally: print "=== inside chdir ka finally" chdir(FULL_PATH); resume_file = '%s/%s.tex' % (destination_dir, prn) #now store the person's generated resume-latex-code f = file(resume_file,'w'); #if the file exists, overwrite it ELSE create it. f.write(t.render(c)); f.close(); #now update the .tex generation timestamp print "Updating the resume details timestamp with what has been done"; print s; print "Now is ", datetime.now(); r = resume.objects.get_or_create(prn=s); print "====latex======== resume made ",r #because we called get_or_create, we will get a tuple containing the record and a bool value telling whether it was created or fetched r[0].last_tex_generated = datetime.now(); print r[0].last_tex_generated r[0].save(); """#for now postponed to next release #now add this file to version control hg_command = "hg add %s; hg commit -u laresumex -m 'updated by %s' " % (resume_file,user); return_status = get_done(hg_command); """ return_status = True; except Exception as e: print '=====latex============ Exception was ', e; return_status = False; finally: if return_status is False: output = "<h3>Couldn't generate your .TEX file! Return code was %d </h3>" % return_status; else: output = "<h3>Done!</h3>"; else: output = "<h3>Student details for PRN %s not found!</h3>" % (prn); else: output = "<h3>Hey, pass me a PRN man!</h3>"; return HttpResponse(output);
def get_students_name(request): if 'username' not in request.session: request.session['redirect'] = request.get_full_path(); return our_redirect('/login') g = group.objects.get(name='placement committee') if user(request.session['username']) not in g.user_set.all(): return HttpResponse('not for u'); post = request.POST; print post.lists(); for a,v in post.iteritems(): print a,"======",v,"===",type(v) name_list=[] if 'company_name' in post: com=company.objects.get(name=post['company_name']); print "COMPANY ======",com name_list=list(); for g in com.students_applied.all(): name_list.append(g); spreadsheet_name = "SICSR-%s-applicants.xls" % (com.name.replace(' ','-')); else: p =[] for g,v in post.iteritems(): if g.startswith('groups_'): s = v.split(','); for prn in s: if prn is not "": p.append(prn) print p s = student.objects.filter(prn__in = p); name_list.extend(s); spreadsheet_name = "SICSR-students.xls"; print "List of students is ",name_list; if name_list: #now we will make a spreadsheet of this data. wb = Workbook(); ws0 = wb.add_sheet('Applicants from SICSR'); #actually, this is going to come from the person who is selecting the list of students. fields_to_get=dict() for f,v in request.POST.iteritems(): if f.startswith('criteria'): fields_to_get[int(f[9:])]=v print "Fields ro get", fields_to_get if len(fields_to_get) is 0: return HttpResponse('Check Some Fields to be sent to the company') #print headings in the spreadsheet full = get_full_list(); for f in fields_to_get.keys(): print "title == ", full[f]['display_name']; ws0.write(0,f,full[f]['display_name']); #print data in the spreadsheet for x in range(len(name_list)): print "X is ...", x, "and s is ...", # x is the students name list ka index s=name_list[x] print "for student", s for y in fields_to_get.keys(): #hardcoding 4 fields currently try: # y is the fields ka index print "fields to get. ....",fields_to_get[y] si=fields_to_get[y].split('_'); print "SI ======", si; if si[0] == 'student': data = s.__getattribute__(si[1]) print "==data===",data elif si[0] == "personal" or si[0] == "swExposure": table= eval(si[0]).objects.get(primary_table=s); data = str(table.__getattribute__(si[1])) elif si[0] == 'workex': data=s.total_workex(); elif si[0] == 'companySpecific': cs=eval(si[0]).objects.get(key = si[1]) csd = companySpecificData.objects.filter(primary_table = s).filter(valueOf = cs)[0]; print "CS =====",cs,"CSD =========",csd data = csd.value; else: if si[1] == 'graduation': table=marks.get_graduation_course(s) data = str(table) else: table= eval(si[0]).objects.filter(primary_table=s).filter(course=si[1])[0]; print "we are using table ", table data = str(table.get_percentage()); except Exception as e: print "==========HAD GOT an EXCEPTION ;)", e data = "---" pass; #data = eval("name_list[%d].%s" % (x,fields_to_get[y])); print "Writing data %s at %d %d" % (data,x,y); ws0.write(x+1,y,data); wb.save('/tmp/%s' % (spreadsheet_name)); copy_spreadsheet_command = "cp -v /tmp/%s %s" % (spreadsheet_name,MEDIA_ROOT); get_done(copy_spreadsheet_command); #get the resume collection of these students too. #TODO: move this method to the model, making it static. #import pdb; #pdb.set_trace(); resumes_list = [] for n in name_list: try: r = resume.objects.get(prn=n); if r is None: r = pisapdf(request,n,get_PDF_directly=False) except resume.DoesNotExist as e: r = pisapdf(request,n,get_PDF_directly=False); resumes_list.append(r); t = loader.get_template('company/students_list.html') c = Context({ 'students_applied':name_list, 'spreadsheet_link':MEDIA_URL+'/'+spreadsheet_name, 'ROOT':ROOT, }) return HttpResponse(t.render(c))
def latex(request, prn): if 'username' not in request.session: request.session['redirect'] = request.get_full_path() return our_redirect('/ldap_login/') '''generates the resume and puts it into the resume store for version control''' #the current user from session; if prn != request.session['username']: return HttpResponse('Please mind your own resume...') if prn is not None: try: s = student.objects.get(pk=str(prn)) print "=============== inside Latex.. found S .....", s except Exception as e: print "======inside latex... exception", e output = "<h3>Student details for PRN %s not found! Can't generate a LaTeX file!</h3>" % ( prn) return HttpResponse(output) if s is not None: print "==latex====s is not NOne" #pass the student object with all his entered info to the template generator t = loader.get_template('%s/template.tex' % RESUME_FORMAT) print "=====latex ===t ", t #add the basic info wala original object also student_data = tables.get_tables(s) #student_data['photo'] = RESUME_STORE + "photos/" + prn + ".png" student_data['photo'] = "%s.png" % (prn) pprint(student_data) c = Context(student_data) try: print " =latex==== inside the try" #every latex file goes into that prn's directory destination_dir = '%s/%s/' % (RESUME_STORE, prn) try: chdir(destination_dir ) #if we can't change into it, create it! except OSError: print "===latex === Os Error aya tha.. making dIr" mkdir(destination_dir) finally: print "=== inside chdir ka finally" chdir(FULL_PATH) resume_file = '%s/%s.tex' % (destination_dir, prn) #now store the person's generated resume-latex-code f = file(resume_file, 'w') #if the file exists, overwrite it ELSE create it. f.write(t.render(c)) f.close() #now update the .tex generation timestamp print "Updating the resume details timestamp with what has been done" print s print "Now is ", datetime.now() r = resume.objects.get_or_create(prn=s) print "====latex======== resume made ", r #because we called get_or_create, we will get a tuple containing the record and a bool value telling whether it was created or fetched r[0].last_tex_generated = datetime.now() print r[0].last_tex_generated r[0].save() """#for now postponed to next release #now add this file to version control hg_command = "hg add %s; hg commit -u laresumex -m 'updated by %s' " % (resume_file,user); return_status = get_done(hg_command); """ return_status = True except Exception as e: print '=====latex============ Exception was ', e return_status = False finally: if return_status is False: output = "<h3>Couldn't generate your .TEX file! Return code was %d </h3>" % return_status else: output = "<h3>Done!</h3>" else: output = "<h3>Student details for PRN %s not found!</h3>" % (prn) else: output = "<h3>Hey, pass me a PRN man!</h3>" return HttpResponse(output)
def pdf(request, prn): if 'username' not in request.session: request.session['redirect'] = request.get_full_path() return our_redirect('/ldap_login/') if prn != request.session['username']: return HttpResponse('Not your resume!') if prn is not None: try: s = student.objects.get(pk=str(prn)) print "We have got a student ", s try: r = resume.objects.get(prn=s) except Exception as e: #no resume was ever created for this user, hence we need to generate atleast latex once. print "====pdf==== Resume record doesn't exist...calling latex()" latex(request, prn) finally: r = resume.objects.get(prn=s) print "======pdf======= Ok, now we have ", r except Exception as e: output = "<h3>Student details for PRN %s not found! Can't generate a PDF!</h3>" % ( prn) print "=======pdf ========", e return HttpResponse(output) print "Last TEX generated ", r.last_tex_generated print "Last PDF generated ", r.last_pdf_generated #compare generate_resume.models.resume.last_tex_generated with student_info.models.student_last_updated and decide! tex_file = "%s/%s/%s.tex" % (RESUME_STORE, prn, prn) #do we have a fresher .TEX file compared to the infromation filled by the student ? if (r.last_tex_generated is not None) and (r.last_tex_generated < s.last_update) or ( not (path.exists(tex_file))): #oh no! it isn't fresher! generate it again! print "we have got a stale .TEX file! regenerating it by calling latex" latex(request, prn) else: #ok, there is no need to regenerate latex pass #Now...is the pdf file fresher ? pdf_file = "%s/%s/%s.pdf" % (RESUME_STORE, prn, prn) if (r.last_pdf_generated is not None) and (r.last_pdf_generated > r.last_tex_generated ) and (path.exists(pdf_file)): #the pdf file is fresher, so we don't need to regenerate it! let's just give it back. print "PDF file for %s is already fresher, so giving it back directly!" % ( r.prn) else: print "PDF file is stale!" #the pdf file is stale, get a fresh copy! #generate it's pdf pdf_file = "/tmp/%s.pdf" % (prn) return_status = False #find the tex file try: #generate the pdf copy_photo_command = "cp -v %s/photos/%s.* %s/%s/" % ( RESUME_STORE, prn, RESUME_STORE, prn) get_done(copy_photo_command) pdf_generation_command = "pdflatex --interaction=nonstopmode -etex -output-directory=/tmp %s/%s/%s.tex" % ( RESUME_STORE, prn, prn) for i in range( 0, 3 ): #run the pdflatex command min 2 and max 3 times -- Manjusha Mam, Bhaskaracharya Pratishthana print "===========>PASS %d<===========" % (i) return_status = get_done(pdf_generation_command) #print "Return status is ",return_status; #doesn't matter now...after get done. pdf_file = "/tmp/%s.pdf" % prn copy_pdf_command = "cp -v /tmp/%s.pdf %s/%s/" % ( prn, RESUME_STORE, prn) #copy the .pdf to the user's directory in STORE so that we can reuse it get_done(copy_pdf_command) print "Updating timestamp for the PDF generation in our records" r.last_pdf_generated = datetime.now() r.save() except Exception as e: response = HttpResponse("Some problem!") print 'Exception was ', e #open the generated pdf file resume_pdf = open(pdf_file) #prepare the file to be sent response = HttpResponse(resume_pdf.read(), mimetype="application/pdf") resume_pdf.close() #name the file properly response[ 'Content-Disposition'] = "attachment; filename=SICSR_%s_resume.pdf" % s.fullname else: output = "<h3>Hey, pass me a PRN man!</h3>" response = HttpResponse(output) return response
def nayeforms(request, prn): #login checker if "username" not in request.session: print "No session found!" request.session['redirect'] = request.get_full_path() return our_redirect("/login") elif prn != request.session['username']: print "prn", prn, type(prn) print "username", request.session['username'], type( request.session['username']) return HttpResponse('<b>Please edit your own form! :@</b>') from student_info.forms import PersonalForm, MarksForm, SwExposureForm, CertificationForm, WorkexForm, AcademicAchievementsForm, ProjectForm, ExtraCurricularForm, StudentForm, AdditionalInfoForm from student_info.models import student, personal, swExposure, marks, certification, workex, academic, project, extracurricular, AdditionalInfo, companySpecific, companySpecificData from django.forms.models import modelformset_factory print "Doing everything for prn", prn #for storing the data from the table data = {} #for storing the factories which generate our formsets formset_factories = {} #for storing the formsets themselves formsets = {} invalid_data = False s = None try: s = student.objects.get(pk=prn) are_we_editing = True except: s = student.objects.create(pk=prn) are_we_editing = False print "Are we editing", are_we_editing if request.method == 'POST': #the form was submitted print 'Processing form submission' #print "===POST===" #print request.POST try: student_data_valid = False other_data_valid = False #formset_factories -- kind of customized factories of forms for each of our models formset_factories['marks'] = modelformset_factory(marks, form=MarksForm, extra=0, can_delete=True) formset_factories['personal'] = modelformset_factory( personal, form=PersonalForm, extra=0) formset_factories['swExposure'] = modelformset_factory( swExposure, form=SwExposureForm, extra=0) formset_factories['certification'] = modelformset_factory( certification, form=CertificationForm, extra=0, can_delete=True) formset_factories['workex'] = modelformset_factory(workex, form=WorkexForm, extra=0, can_delete=True) formset_factories['academic'] = modelformset_factory( academic, form=AcademicAchievementsForm, extra=0, can_delete=True) formset_factories['project'] = modelformset_factory( project, form=ProjectForm, extra=0, can_delete=True) formset_factories['extracurricular'] = modelformset_factory( extracurricular, form=ExtraCurricularForm, extra=0, can_delete=True) formset_factories['additionalInfo'] = modelformset_factory( AdditionalInfo, form=AdditionalInfoForm, extra=0, can_delete=True) #generate a formset -- collection of forms for editing/creating new data formsets['marks'] = formset_factories['marks'](request.POST, prefix='marks') formsets['personal'] = formset_factories['personal']( request.POST, prefix='personal') formsets['swExposure'] = formset_factories['swExposure']( request.POST, prefix='swExposure') formsets['certification'] = formset_factories['certification']( request.POST, prefix='certification') formsets['workex'] = formset_factories['workex'](request.POST, prefix='workex') formsets['academic'] = formset_factories['academic']( request.POST, prefix='academic') formsets['project'] = formset_factories['project']( request.POST, prefix='project') formsets['extracurricular'] = formset_factories['extracurricular']( request.POST, prefix='extracurricular') formsets['additionalInfo'] = formset_factories['additionalInfo']( request.POST, prefix='additionalInfo') sf = StudentForm(request.POST, request.FILES, prefix='student', instance=s) print 'Starting to save data' print 'Processing Company Specific info' #WORST way of identifiying Company Specific fields for processing -- but can't find a better way, for now. for field, value in request.POST.lists(): field_name = field.split('_') print "Field ", field print "Value ", value if (field_name[0] == 'companySpecific'): try: print 'On', field, 'and Data', value cs = companySpecific.objects.get(key=field_name[1]) print "\n\n\nCOMPANY SPECIFIC...!!!!!!...", value, type( value) final_value = str(value[0]) for v in value[1:]: final_value += ',' + v csd, created_or_found = companySpecificData.objects.get_or_create( valueOf=cs, primary_table=s) csd.value = value csd.save() print 'Saving Company Specific Data' other_data_valid = True except Exception as e: print "===================" print "Error with Company data :", print e other_data_valid = False #Add the error message to be displayed in the template messages.error(request, "<b>Company Specific Info :</b> %s" % e) #raise exception so that we can go back to displaying the form raise Exception print 'Processing student data', student_data_valid = sf.is_valid() if student_data_valid: print 'Saved all submitted data for Student Basic info' sf.save() else: print "===================" print "Error with Student data :", print sf.errors #Add the error message to be displayed in the template messages.error(request, "<b>Basic Information: </b>%s" % sf.errors) #raise exception so that we can go back to displaying the form raise Exception print 'Student data validity status : %s' % student_data_valid for f in formsets: #formsets[f].clean() print 'Processing ', f other_data_valid = formsets[f].is_valid() if other_data_valid: instances = formsets[f].save(commit=False) for i in instances: i.primary_table = s i.save() print 'Saved all submitted data for ', f else: #Error!! print "===================" print "Error with %s is :" % (f) print formsets[f].errors print 'Other data validity status is : %s' % other_data_valid #Add the error message to be displayed in the template messages.error( request, "<b>%s :</b> %s " % (f.title(), formsets[f].errors)) #raise exception so that we can go back to displaying the form raise Exception except: if (not student_data_valid) and ( not are_we_editing ): #we were trying to save a NEW student's data and encountered problem print 'Student data is invalid and we are creating new record', s.delete() elif (not student_data_valid) and ( are_we_editing ): #we were trying to save a OLD student's data and encountered errors print 'Student data is invalid and we are editing', pass #the data wasn't actually saved because of django's mechanisms elif (not other_data_valid) and (not are_we_editing): print "Figure out what to do in case tehre are errors in saving NEW data for a student in various models" pass elif (not other_data_valid) and (are_we_editing): print 'Other data is invalid and we are editing existing details' pass #the data wasn't actually saved because of django's mechanisms if student_data_valid and other_data_valid: return our_redirect('/common/Submitted/done') else: #Company Specific fields -- special thingys ;) #These provide dynamic fields in the form which can be added in the form by the placement team. #existing data for company specific fields data['companySpecificData'] = companySpecificData.objects.filter( primary_table=s).order_by('valueOf') already_filled_list = data['companySpecificData'].values_list( 'valueOf') #provide for new fields to be displayed to user #here we select only those fields which haven't been filled by the user as obtained in the above list. #basically this is a query which says --> #"Give me all Company Specific fields excluding those whose values have been filled by the user and order them by their displayText" data['companySpecificFields'] = companySpecific.objects.all( ).exclude(fieldType='special').exclude( id__in=already_filled_list).order_by('displayText') print "Invalid data! Returning form for editing" else: #new form is being displayed print 'Displaying new/edit form' data['marks'] = marks.objects.filter(primary_table=prn) if data['marks'].count() == 0: #no existing data for this student print "No existing marks data found for this student" formset_factories['marks'] = modelformset_factory( marks, form=MarksForm, exclude=('primary_table'), extra=3, can_delete=True) formsets['marks'] = formset_factories['marks']( prefix='marks', queryset=data['marks']) else: formset_factories['marks'] = modelformset_factory(marks, form=MarksForm, extra=0, can_delete=True) formsets['marks'] = formset_factories['marks']( prefix='marks', queryset=data['marks']) data['personal'] = personal.objects.filter(primary_table=prn) if data['personal'].count() == 0: print "No existing personal data found for this student" formset_factories['personal'] = modelformset_factory( personal, form=PersonalForm, extra=1) formsets['personal'] = formset_factories['personal']( prefix='personal', queryset=data['personal']) else: formset_factories['personal'] = modelformset_factory( personal, form=PersonalForm, extra=0) formsets['personal'] = formset_factories['personal']( prefix='personal', queryset=data['personal']) data['swExposure'] = swExposure.objects.filter(primary_table=prn) if data['swExposure'].count() == 0: print "No existing software exposure data found for this student" formset_factories['swExposure'] = modelformset_factory( swExposure, form=SwExposureForm, extra=1) formsets['swExposure'] = formset_factories['swExposure']( prefix='swExposure', queryset=data['swExposure']) else: formset_factories['swExposure'] = modelformset_factory( swExposure, form=SwExposureForm, extra=0) formsets['swExposure'] = formset_factories['swExposure']( prefix='swExposure', queryset=data['swExposure']) data['certification'] = certification.objects.filter(primary_table=prn) if data['certification'].count() == 0: print "No existing certification data found for this student" formset_factories['certification'] = modelformset_factory( certification, form=CertificationForm, extra=1, can_delete=True) formsets['certification'] = formset_factories['certification']( prefix='certification', queryset=data['certification']) else: formset_factories['certification'] = modelformset_factory( certification, form=CertificationForm, extra=0, can_delete=True) formsets['certification'] = formset_factories['certification']( prefix='certification', queryset=data['certification']) data['workex'] = workex.objects.filter(primary_table=prn) if data['workex'].count() == 0: print "No existing workex data found for this student" formset_factories['workex'] = modelformset_factory(workex, form=WorkexForm, extra=1, can_delete=True) formsets['workex'] = formset_factories['workex']( prefix='workex', queryset=data['workex']) else: formset_factories['workex'] = modelformset_factory(workex, form=WorkexForm, extra=0, can_delete=True) formsets['workex'] = formset_factories['workex']( prefix='workex', queryset=data['workex']) data['academic'] = academic.objects.filter(primary_table=prn) if data['academic'].count() == 0: print "No existing academic data found for this student" formset_factories['academic'] = modelformset_factory( academic, form=AcademicAchievementsForm, extra=1, can_delete=True) formsets['academic'] = formset_factories['academic']( prefix='academic', queryset=data['academic']) else: #existing data was found for this student formset_factories['academic'] = modelformset_factory( academic, form=AcademicAchievementsForm, extra=0, can_delete=True) formsets['academic'] = formset_factories['academic']( prefix='academic', queryset=data['academic']) data['project'] = project.objects.filter(primary_table=prn) if data['project'].count() == 0: print "No existing project data found for this student" formset_factories['project'] = modelformset_factory( project, form=ProjectForm, extra=1, can_delete=True) formsets['project'] = formset_factories['project']( prefix='project', queryset=data['project']) else: #existing data was found for this student formset_factories['project'] = modelformset_factory( project, form=ProjectForm, extra=0, can_delete=True) formsets['project'] = formset_factories['project']( prefix='project', queryset=data['project']) data['extracurricular'] = extracurricular.objects.filter( primary_table=prn) if data['extracurricular'].count() == 0: print "No existing extracurricular data found for this student" formset_factories['extracurricular'] = modelformset_factory( extracurricular, form=ExtraCurricularForm, extra=1, can_delete=True) formsets['extracurricular'] = formset_factories['extracurricular']( prefix='extracurricular', queryset=data['extracurricular']) else: #existing data was found for this student formset_factories['extracurricular'] = modelformset_factory( extracurricular, form=ExtraCurricularForm, extra=0, can_delete=True) formsets['extracurricular'] = formset_factories['extracurricular']( prefix='extracurricular', queryset=data['extracurricular']) data['additionalInfo'] = AdditionalInfo.objects.filter( primary_table=prn) if data['additionalInfo'].count() == 0: print "No existing additionalInfo data found for this student" formset_factories['additionalInfo'] = modelformset_factory( AdditionalInfo, form=AdditionalInfoForm, extra=1, can_delete=True) formsets['additionalInfo'] = formset_factories['additionalInfo']( prefix='additionalInfo', queryset=data['additionalInfo']) else: #existing data was found for this student formset_factories['additionalInfo'] = modelformset_factory( AdditionalInfo, form=AdditionalInfoForm, extra=0, can_delete=True) formsets['additionalInfo'] = formset_factories['additionalInfo']( prefix='additionalInfo', queryset=data['additionalInfo']) #Company Specific fields -- special thingys ;) #These provide dynamic fields in the form which can be added in the form by the placement team. #existing data for company specific fields data['companySpecificData'] = companySpecificData.objects.filter( primary_table=s).order_by('valueOf') already_filled_list = data['companySpecificData'].values_list( 'valueOf') #provide for new fields to be displayed to user #here we select only those fields which haven't been filled by the user as obtained in the above list. #basically this is a query which says --> #"Give me all Company Specific fields excluding those whose values have been filled by the user and order them by their displayText" data['companySpecificFields'] = companySpecific.objects.all().exclude( fieldType='special').exclude( id__in=already_filled_list).order_by('displayText') #Student Data data['student'] = s sf = StudentForm(prefix='student', instance=data['student']) t = loader.get_template('student_info/nayeforms.html') context = { 'prn': prn, 'marks_formset': formsets['marks'], 'personal_formset': formsets['personal'], 'swExposure_formset': formsets['swExposure'], 'certification_formset': formsets['certification'], 'workex_formset': formsets['workex'], 'academic_formset': formsets['academic'], 'project_formset': formsets['project'], 'extracurricular_formset': formsets['extracurricular'], 'additionalInfo_formset': formsets['additionalInfo'], 'student_form': sf, 's': s, #student object 'ROOT': ROOT, 'companySpecificData': data['companySpecificData'], 'companySpecificFields': data['companySpecificFields'], } c = RequestContext(request, context) return HttpResponse(t.render(c))
def got_placed(request): if 'username' not in request.session: request.session['redirect'] = request.get_full_path() return our_redirect('/ldap_login/') #if 'POST' not in request: # print 'no post' count = student.objects.all().count() try: placed_id = request.POST['what'] filter = request.POST['filter'] except KeyError: #return HttpResponse('PLease fill all fields') return render_to_response('admin/reportsmenu.html', {'ROOT': ROOT}, context_instance=RequestContext(request)) def mkdict(stu, type): lala = [] for items in stu: toreturn = {} toreturn['other'] = items if type == 0: # items[0].__class__.__name__ = 'student' toreturn['company'] = items.company u = user.objects.get(username=items.student.prn) else: print items u = user.objects.get(username=items.prn) toreturn['group'] = u.groups.all()[0] lala.append(toreturn) return lala #g = group.objects.get(name='placement committee') #there might be a case when there would be no role in the session!! -- though we need to correct and avoid such a case actually! if (not request.session.has_key('role')) or (request.session['role'] != 'admin'): return HttpResponse('not for u') placed_stu = placement_in.objects.all() from operator import itemgetter a = lambda (x): itemgetter(filter)(x).__str__() if placed_id == 'placed': label = ['placed', 'unplaced'] context = { 'placed': 'yes', 'PS': sorted(mkdict(placed_stu, 0), key=a) } elif placed_id == 'unplaced': slist = [] label = ['unplaced', 'placed'] for p in placed_stu: slist.append(p.student.prn) unplaced_stu = student.objects.exclude(prn__in=slist) context = { 'placed': 'no', 'UPS': sorted(mkdict(unplaced_stu, 1), key=a) } try: leng = len(context['UPS']) print context['UPS'] except: leng = len(context['PS']) print context['PS'] context['count'] = count context['fil'] = filter #because flter is a keyword i think context['ROOT'] = ROOT c = Context(context) t = loader.get_template('company/got_placed.html') print "=========", request.get_full_path() return HttpResponse(t.render(c))
def logout(request): '''logs you out, duh!''' auth_logout(request) return our_redirect('/')
def passwordHelp(request): if 'username' in request.session: return our_redirect('/home'); else: return render_to_response('ldap_login/passwordhelp.html');
def get_students_name(request): if 'username' not in request.session: request.session['redirect'] = request.get_full_path() return our_redirect('/login') g = group.objects.get(name='placement committee') if user(request.session['username']) not in g.user_set.all(): return HttpResponse('not for u') post = request.POST print post.lists() for a, v in post.iteritems(): print a, "======", v, "===", type(v) name_list = [] if 'company_name' in post: com = company.objects.get(name=post['company_name']) print "COMPANY ======", com name_list = list() for g in com.students_applied.all(): name_list.append(g) spreadsheet_name = "SICSR-%s-applicants.xls" % (com.name.replace( ' ', '-')) else: p = [] for g, v in post.iteritems(): if g.startswith('groups_'): s = v.split(',') for prn in s: if prn is not "": p.append(prn) print p s = student.objects.filter(prn__in=p) name_list.extend(s) spreadsheet_name = "SICSR-students.xls" print "List of students is ", name_list if name_list: #now we will make a spreadsheet of this data. wb = Workbook() ws0 = wb.add_sheet('Applicants from SICSR') #actually, this is going to come from the person who is selecting the list of students. fields_to_get = dict() for f, v in request.POST.iteritems(): if f.startswith('criteria'): fields_to_get[int(f[9:])] = v print "Fields ro get", fields_to_get if len(fields_to_get) is 0: return HttpResponse('Check Some Fields to be sent to the company') #print headings in the spreadsheet full = get_full_list() for f in fields_to_get.keys(): print "title == ", full[f]['display_name'] ws0.write(0, f, full[f]['display_name']) #print data in the spreadsheet for x in range(len(name_list)): print "X is ...", x, "and s is ...", # x is the students name list ka index s = name_list[x] print "for student", s for y in fields_to_get.keys(): #hardcoding 4 fields currently try: # y is the fields ka index print "fields to get. ....", fields_to_get[y] si = fields_to_get[y].split('_') print "SI ======", si if si[0] == 'student': data = s.__getattribute__(si[1]) print "==data===", data elif si[0] == "personal" or si[0] == "swExposure": table = eval(si[0]).objects.get(primary_table=s) data = str(table.__getattribute__(si[1])) elif si[0] == 'workex': data = s.total_workex() elif si[0] == 'companySpecific': cs = eval(si[0]).objects.get(key=si[1]) csd = companySpecificData.objects.filter( primary_table=s).filter(valueOf=cs)[0] print "CS =====", cs, "CSD =========", csd data = csd.value else: if si[1] == 'graduation': table = marks.get_graduation_course(s) data = str(table) else: table = eval(si[0]).objects.filter( primary_table=s).filter(course=si[1])[0] print "we are using table ", table data = str(table.get_percentage()) except Exception as e: print "==========HAD GOT an EXCEPTION ;)", e data = "---" pass #data = eval("name_list[%d].%s" % (x,fields_to_get[y])); print "Writing data %s at %d %d" % (data, x, y) ws0.write(x + 1, y, data) wb.save('/tmp/%s' % (spreadsheet_name)) copy_spreadsheet_command = "cp -v /tmp/%s %s" % (spreadsheet_name, MEDIA_ROOT) get_done(copy_spreadsheet_command) #get the resume collection of these students too. #TODO: move this method to the model, making it static. #import pdb; #pdb.set_trace(); resumes_list = [] for n in name_list: try: r = resume.objects.get(prn=n) if r is None: r = pisapdf(request, n, get_PDF_directly=False) except resume.DoesNotExist as e: r = pisapdf(request, n, get_PDF_directly=False) resumes_list.append(r) t = loader.get_template('company/students_list.html') c = Context({ 'students_applied': name_list, 'spreadsheet_link': MEDIA_URL + '/' + spreadsheet_name, 'ROOT': ROOT, }) return HttpResponse(t.render(c))