def forgot_password(request,email=None): dajax = Dajax() if not email is None and not email == '' : try: validate_email(email) # validate_email is a django inbuilt function that throws ValidationError for wrong email address # Issue: starts with _ not acceptable profile = UserProfile.objects.get(user__email = str(email)) email = profile.user.email user = profile.user if not profile.user.is_active: dajax.script('$.bootstrapGrowl("Activate your account first! Check your mail for the activation link." , {type:"error",delay:20000} );') return dajax.json() mail_template = get_template('email/forgot_password.html') body = mail_template.render( Context( { 'username':user.username, 'SITE_URL':settings.SITE_URL, 'passwordkey':profile.activation_key, })) #if settings.SEND_EMAILS: send_mail('Shaastra2014 password reset request', body,'*****@*****.**', [user.email,], fail_silently=False) dajax.script('$.bootstrapGrowl("An email with a link to reset your password has been sent to your email id: %s", {type:"success",delay:20000} );' % email) dajax.script('$.bootstrapGrowl("Please also check your spam", {type:"danger",delay:20000});') except ValidationError: dajax.script('$.bootstrapGrowl("Your email:%s is invalid", {type:"danger",delay:10000} );' % email) return dajax.json() except: dajax.script('$.bootstrapGrowl("Not a registered email id", {type:"danger",delay:20000} );') return dajax.json() return dajax.json()
def show_event_list(request,choose_form = None): dajax = Dajax() if request.method == 'POST' and choose_form != None: form = ChooseEventForm(deserialize_form(choose_form)) if form.is_valid(): #Basically emulating show_event_erp without checking for errors clean_form = form.clean() event_name = clean_form['event'] generic_event_instance = GenericEvent.objects.get(title = event_name) event_type = generic_event_instance.event_type event_pk = generic_event_instance.pk if event_type == 'Participant': event_instance = ParticipantEvent.objects.get(pk=event_pk) form = ParticipantEventDetailsForm(instance = event_instance) if event_type == 'Audience': event_instance = AudienceEvent.objects.get(pk=event_pk) form = AudienceEventDetailsForm(instance = event_instance) tab_list = Tab.objects.filter(event=event_instance) #context_dict = {'model_instance' : event_instance, 'type' : 'tab', 'form' : form} html_content = render_to_string('events/erp_tabs.html', locals(), RequestContext(request)) dajax.assign("#id_content_right", "innerHTML", html_content) return dajax.json() else: show_alert(dajax,"error","No content has been uploaded for this event") else: form = ChooseEventForm() html_content = render_to_string('events/choose_event.html', locals(),RequestContext(request)) dajax.assign('#id_content_right','innerHTML', html_content) return dajax.json()
def addroom(request,addroom_form=None): dajax = Dajax() if request.method == 'POST' and addroom_form != None: form = AddRoomForm(deserialize_form(addroom_form)) if form.is_valid(): cleaned_form = form.cleaned_data room_num = cleaned_form['room_no'] hostel = cleaned_form['hostel'] already_avail = AvailableRooms.objects.filter(room_no=room_num,hostel=hostel) if already_avail: show_alert(dajax,"error","Room already exists") return dajax.json() else: try: form.save() show_alert(dajax,"success","Room Added Successfully") html_content = render_to_string('hospi/AddRoom.html',locals(),RequestContext(request)) dajax.assign('#tab2',"innerHTML",html_content) return dajax.json() except EditError as error: show_alert(dajax,"error",error.value) return dajax.json() else: show_alert(dajax,"error","Form is invalid") return dajax.json() else: form = AddRoomForm() html_content = render_to_string('hospi/AddRoom.html',locals(),RequestContext(request)) dajax.assign('#tab2',"innerHTML",html_content) return dajax.json()
def change_password(request,form = None): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") if not request.user.is_authenticated(): dajax.script('$.bootstrapGrowl("Login First!", {type:"danger",delay:10000} );') return dajax.json() # print deserialize_form(form) if form is None: dajax.script('$.bootstrapGrowl("Invalid password change request", {type:"danger",delay:10000} );') return dajax.json() form = ChangePasswordForm(deserialize_form(form)) if not form.is_valid(): errdict = dict(form.errors) for error in form.errors: # if str(errdict[error][0])!='This field is required.': dajax.script('$.bootstrapGrowl("%s:: %s" , {type:"error",delay:10000} );'% (str(error),str(errdict[error][0]))) dajax.script("$(\'#form_change_password #id_new_password').val('');$('#form_change_password #id_new_password_again').val('');") return dajax.json() user = request.user if not user.check_password(form.cleaned_data['old_password']): dajax.script('$.bootstrapGrowl("Please check your old password" , {type:"error",delay:10000} );') return dajax.json() user.set_password(form.cleaned_data['new_password']) profile = UserProfile.objects.get(user=request.user) user.save() profile.save() dajax.script('$.bootstrapGrowl("Your password was changed successfully!" , {type:"success",delay:30000} );') #TODO: why is the field not getting empty????? dajax.script('$("#dashboard #form_change_password #id_old_password").val("");') dajax.script('$("#dashboard #form_change_password #id_new_password").val("");') dajax.script('$("#dashboard #form_change_password #id_new_password_again").val("");') return dajax.json()
def choose(request,choose_eventform=None): dajax=Dajax() if request.method=='POST' and choose_eventform != None: form = ChooseEventForm(deserialize_form(choose_eventform)) if form.is_valid(): clean_form = form.clean() event_name = clean_form['event'] generic_event_instance = GenericEvent.objects.get(title = event_name) event_pk = generic_event_instance.pk parti_event_instance = ParticipantEvent.objects.get(pk = event_pk) mins = parti_event_instance.team_size_min maxs = parti_event_instance.team_size_max teamformset = formset_factory(ShaastraIDForm,extra=maxs) data={ 'form-TOTAL_FORMS':u'', 'form-INITIAL_FORMS':u'', 'form-MIN_NUM_FORMS':u'', 'form-MAX_NUM_FORMS':u'', } html_content = render_to_string('hospi/CreateTeam.html',locals(),RequestContext(request)) dajax.assign('#tab6',"innerHTML",html_content) return dajax.json() else: show_alert(dajax,"error","Form invalid") return dajax.json() else: form = ChooseEventForm() html_content = render_to_string('hospi/Choose.html',locals(),RequestContext(request)) dajax.assign('#tab6',"innerHTML",html_content) return dajax.json()
def show_event_tdp(request,teamevent_id=None): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") if teamevent_id is None: dajax.script('$.bootstrapGrowl("Invalid request to view teamevent details", {type:"danger",delay:20000} );') return dajax.json() try: temp = int(teamevent_id) except: dajax.script('$.bootstrapGrowl("Invalid request to view teamevent details", {type:"danger",delay:20000} );') return dajax.json() if not request.user.is_authenticated(): dajax.script('$.bootstrapGrowl("Login to view your event submission details", {type:"danger",delay:20000} );') return dajax.json() else: profile = UserProfile.objects.get(user=request.user) try: team_event = TeamEvent.objects.get(id=int(teamevent_id)) except: dajax.script('$.bootstrapGrowl("Invalid request", {type:"danger",delay:20000} );') return dajax.json() now = timezone.now() context_dict = {'teamevent':team_event,'profile':profile,'now':now,'TDPFileForm':TDPFileForm(),'settings':settings} html_stuff = render_to_string('dashboard/event_tdp_submit.html',context_dict,RequestContext(request)) if html_stuff: dajax.assign('#content_dash','innerHTML',html_stuff) #dajax.script('$("#event_register").modal("show");') return dajax.json()
def add_college(request,college=None,city=None,state=None): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") #: if user has chosen a college in dropdown, depopulate it OR growl if city is None or college is None or state is None or city =='' or college =='' or state =='': dajax.script('$.bootstrapGrowl("Please enter relevant details for adding your college", {type:"danger",delay:10000});') return dajax.json() else: try: College.objects.get(name__iexact=college) dajax.script('$.bootstrapGrowl("Your college is already on our list, please check again", {type:"danger",delay:10000});') return dajax.json() except: coll=None dajax.script('$("#add_college").modal(\'hide\');') dajax.script('$("#login").show();') coll=College(name=college,city=city,state=state) try: if clean_coll(coll.name) and clean_coll(coll.city): coll.save() else: dajax.script('$.bootstrapGrowl("Please refrain from using profanity", {type:"danger",delay:10000});') return dajax.json() except: coll.save() dajax.assign("#add_coll_name",'innerHTML','%s'% college) dajax.assign("#add_coll_result",'innerHTML','College:') #dajax.script("$('#college')[0]value = '%s'" % college) dajax.script('$.bootstrapGrowl("Your college:<strong>%s</strong> was added. Welcome", {type:"success",delay:10000} );'% str(coll.name) ) # : populate the id_college with the given college details? dajax.script("$('#add_coll_message').toggle();") dajax.script("$('#form_registration #id_college').toggle();") dajax.script("$('#add_coll_form').toggle();") # colllist=College.objects.all() return dajax.json()
def show_tdp_submissions(request): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") if not request.user.is_authenticated(): dajax.script('$.bootstrapGrowl("Login to view your registered events", {type:"danger",delay:20000} );') return dajax.json() else: profile = UserProfile.objects.get(user=request.user) team_event_list = profile.get_regd_events() tdp_submission_list = [] for teamevent in team_event_list: if teamevent.get_event().has_tdp and teamevent.has_submitted_tdp: tdp_submission_list.append(teamevent) no_regd = len(tdp_submission_list) now = timezone.now() title_tdp = 'Your successful TDP Submissions' context_dict = {'tdp_submission_list':tdp_submission_list,'profile':profile,'now':now,'no_regd':no_regd,'settings':settings,'title_tdp':title_tdp} html_stuff = render_to_string('dashboard/list_tdp_submission.html',context_dict,RequestContext(request)) if html_stuff: dajax.assign('#content_dash','innerHTML',html_stuff) #dajax.script('$("#event_register").modal("show");') msg_file_upload = request.session.get('file_upload','') if msg_file_upload != '': del request.session['file_upload'] print msg_file_upload print str(msg_file_upload).startswith('TDP Upload Successful') if str(msg_file_upload).startswith('TDP Upload Successful'): dajax.script('$.bootstrapGrowl("%s", {type:"success",delay:20000} );'% msg_file_upload) else: dajax.script('$.bootstrapGrowl("FileUpload Error: %s", {type:"danger",delay:20000} );'% msg_file_upload) return dajax.json()
def choose_event_parti(request,choose_form=None): dajax=Dajax() if request.method=="POST" and choose_form != None: form=ChooseEventForm(deserialize_form(choose_form)) if form.is_valid(): clean_form = form.clean() event_name = clean_form['event'] generic_event_instance = GenericEvent.objects.get(title=event_name) event_pk = generic_event_instance.pk teameventlist = TeamEvent.objects.using(mainsite_db).filter(event_id = event_pk) userlist = [] for team in teameventlist: userlist.append([team.users.all(),team.team_name]) #if exportCSV: #response = HttpResponse(content_type='text/csv') #response['Content-Disposition'] = 'attachment; filename="participants.csv' #writer = csv.writer(response) #writer.writerow(['Name','Username','Email','Mobile','Team Name','College','Shaastra ID','Want Accomodation']) #for user1,team_name in userlist: #for all_users in user1: # writer.writerow([all_users.first_name,all_users.username,all_users.email,all_users.userprofile_set.all()[0].mobile_number,team_name, all_users.userprofile_set.all()[0].college,all_users.userprofile_set.all()[0].shaastra_id,all_users.userprofile_set.all()[0].want_accomodation]) html_content = render_to_string('events/coreshow_reg_part.html',locals(),RequestContext(request)) dajax.assign('#id_content_right','innerHTML',html_content) return dajax.json() else: form=ChooseEventForm() html_content = render_to_string('events/choose_event_reg_part.html',locals(),RequestContext(request)) dajax.assign('#id_content_right','innerHTML',html_content) return dajax.json()
def select_event_type(request, event_name=None, event_pk=None, event_type_selected=None): """ This function changes type of the event from GenericEvent to Audience or Participant event based on input from the coord You can query based on name or pk. """ dajax = Dajax() json_dict = {} event_instance = None # Argument validation if not ( event_name or event_pk ): # Neither arg given show_alert(dajax, "error", "There is some error on the site, please report to WebOps team") return dajax.json() elif event_name and event_pk: # Both args given .. show_alert(dajax, "error", "There is some error on the site, please report to WebOps team.") return dajax.json() elif event_pk: event_query = GenericEvent.objects.filter(pk=event_pk) elif event_name: event_query = GenericEvent.objects.filter(title=event_name) if event_query: generic_event_instance = event_query[0] event_pk = generic_event_instance.pk event_instance = GenericEvent.objects.get(pk=event_pk) else: show_alert(dajax, "error", "This event has not been created on the site. Contact WebOps team.") return dajax.json() if event_type_selected: if event_type_selected=='Participant': p_event_instance = ParticipantEvent() p_event_instance.pk = event_instance.pk p_event_instance.title = event_instance.title p_event_instance.category = event_instance.category p_event_instance.event_type = 'Participant' p_event_instance.save() request.user.get_profile().event = p_event_instance #form = ParticipantEventDetailsForm(deserialize_form(edit_form), instance = event_instance) elif event_type_selected=='Audience': a_event_instance = AudienceEvent() a_event_instance.pk = event_instance.pk a_event_instance.title = event_instance.title a_event_instance.category = event_instance.category a_event_instance.event_type = 'Audience' a_event_instance.save() request.user.get_profile().event = a_event_instance dajax.script("location.reload();") else: context_dict = {'model_instance' : event_instance} html_content = render_to_string('events/select_event_type.html', context_dict, RequestContext(request)) dajax.assign("#id_content_right", "innerHTML", html_content) # Populate content return dajax.json()
def add_member(request,shaastra_id = None,teamevent_id = None): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") if not request.user.is_authenticated(): dajax.script('$.bootstrapGrowl("Login First",{type:"danger",delay:10000})') return dajax.json() if teamevent_id is None or shaastra_id is None: dajax.script('$.bootstrapGrowl("Invalid request",{type:"danger",delay:10000})') return dajax.json() try: teamevent = TeamEvent.objects.get(id = teamevent_id) print shaastra_id user = UserProfile.objects.get(shaastra_id = shaastra_id).user if request.user not in teamevent.users.all(): dajax.script('$.bootstrapGrowl("Invalid request: user not part of team",{type:"danger",delay:10000})') #Malicious attempt!? return dajax.json() if user in teamevent.users.all(): dajax.script('$.bootstrapGrowl("Invalid request: User is already on the team, you cannot add again.",{type:"danger",delay:10000})') return dajax.json() #User cannot be added if on another team msg,team_name = has_team(user,teamevent.event_id) if msg == 'has_team': dajax.script('$.bootstrapGrowl("Invalid request: User is already on another team for this event. Multiple entries are prohibited. ",{type:"danger",delay:10000})') return dajax.json() #The below statement will not be used, but, for malicious attempts to modify input params, we need it if user.username == request.user.username: dajax.script('$.bootstrapGrowl("Invalid request: You are already on the team.",{type:"danger",delay:10000})') return dajax.json() if teamevent.size() == teamevent.get_event().team_size_max: dajax.script('$.bootstrapGrowl("Sorry. Add member failed.You cannot have more than %s team members in your team.",{type:"danger",delay:10000})'% teamevent.get_event().team_size_min) return dajax.json() teamevent.users.add(user) teamevent.save() msg_update = 'Teammate %s was add to team %s for event %s on %s by %s'%(user.get_full_name(),teamevent.team_name,teamevent.get_event().title,str(timezone.now()),request.user.get_full_name()) for user_team in teamevent.users.all(): if not user_team.username == user.username: update = Update(tag = 'Team Edit',content = msg_update,user = user_team) update.save() msg_update_user = '******'%(teamevent.team_name,teamevent.get_event().title,str(timezone.now()),user.get_full_name()) update = Update(tag = 'Team Add',content = msg_update_user,user = user) update.save() dajax.script('$.bootstrapGrowl("Addition success! %s has been added as a member of team %s",{type:"info",delay:10000,width:"auto"})'% (user.get_full_name(),teamevent.team_name)) #TODO: Update create html_stuff = render_to_string('dashboard/welcome.html',{},RequestContext(request)) if html_stuff: dajax.assign('#content_dash','innerHTML',html_stuff) return dajax.json() except: dajax.script('$.bootstrapGrowl("Invalid request. Check Shaastra ID entered",{type:"danger",delay:10000})') return dajax.json() return dajax.json()
def register(request,reg_form=None,coll_form=None): dajax=Dajax() if request.method=='POST': form = RegistrationForm(deserialize_form(reg_form)) collegeform = CollegeForm(deserialize_form(coll_form)) if form.is_valid(): if not collegeform.is_valid(): collist = form.cleaned_data['college'].split('|') collquery = College.objects.using(mainsite_db).filter(name = collist[0],city=collist[1], state=collist[2]) if collquery.count(): college=collquery[0] else: college = College(name=collist[0],city=collist[1],state=collist[2]) college.save(using='mainsite') else: college = collegeform.instance college.save(using='mainsite') cleaned_form = form.cleaned_data shaastraid = cleaned_form['shaastra_id'] if not id_in_db(shaastraid): new_user = User(first_name=cleaned_form['first_name'],last_name=cleaned_form['last_name'],username=cleaned_form['username'],email=cleaned_form['email']) new_user.set_password('default') new_user.is_active = True new_user.save(using='mainsite') userprofile = UserProfile(user=new_user, gender = cleaned_form['gender'], branch = cleaned_form['branch'], age = cleaned_form['age'], mobile_number = cleaned_form['mobile_number'], college_roll = cleaned_form['college_roll'], college = college, shaastra_id = shaastraid, ) userprofile.save(using='mainsite') else: userprofile = get_userprofile(shaastraid) userprofile.gender = cleaned_form['gender'] userprofile.branch = cleaned_form['branch'] userprofile.age = cleaned_form['age'] userprofile.mobile_number = cleaned_form['mobile_number'] userprofile.college_roll = cleaned_form['college_roll'] userprofile.college = college userprofile.save(using='mainsite') new_form = IndividualForm(initial={'shaastra_ID':shaastraid}) html_content = render_to_string('hospi/Checkin_form.html',locals(),RequestContext(request)) dajax.assign('#tab3',"innerHTML",html_content) return dajax.json() else: show_alert(dajax,"error","Form is invalid") return dajax.json()
def add_member_form(request,teamevent_id = None): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") if teamevent_id is None: return dajax.json() try: teamevent = TeamEvent.objects.get(id = teamevent_id) except: return dajax.json() html_stuff = render_to_string('dashboard/add_member.html',{'teamevent':teamevent},RequestContext(request)) if html_stuff: dajax.assign('#content_dash','innerHTML',html_stuff) return dajax.json()
def change_password_form(request): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") #: if user has chosen a college in dropdown, depopulate it OR growl if not request.user.is_authenticated(): dajax.script('$.bootstrapGrowl("Login First!", {type:"danger",delay:10000} );') return dajax.json() profile = UserProfile.objects.get(user=request.user) change_password_form = ChangePasswordForm() context_dict = {'form_change_password':change_password_form,'profile':profile,'settings':settings} html_stuff = render_to_string('dashboard/change_password.html',context_dict,RequestContext(request)) if html_stuff: dajax.assign('#content_dash','innerHTML',html_stuff) #dajax.script('$("#event_register").modal("show");') return dajax.json()
def edit_profile_password(request, form=None): """ Used to give Dajax(ice) the change password page Renders in : modal Refreshes : right_content """ dajax = Dajax() errors = False userprofile = request.user.get_profile() fullname = userprofile.user.get_full_name() nickname = userprofile.nickname if request.method == 'POST' and form != None: form = PasswordChangeForm(userprofile.user, deserialize_form(form)) if form.is_valid(): form.save() dajax.remove_css_class('#profile_edit_form input', 'error') dajax.script('modal_hide()') # Hide modal show_alert(dajax, 'success', 'Password was changes successfully') else: errors = True dajax.remove_css_class('#profile_edit_form input', 'error') for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') print "errors :", [i for i in form.errors] #show_alert(dajax, 'error', "There were errors in the form") # as it is in modal, not req else: form = PasswordChangeForm ( userprofile.user ) html_content = render_to_string("users/passwd_form.html", locals(), RequestContext(request)) dajax.assign("#id_modal", "innerHTML", html_content) # Populate modal return dajax.json()
def edit_profile(request, form=None): """ Used to give Dajax(ice) the edit profile page Renders in : modal Refreshes : right_content """ dajax = Dajax() errors = False userprofile = request.user.get_profile() fullname = userprofile.user.get_full_name() nickname = userprofile.nickname if request.method == 'POST' and form != None: form = EditProfileForm(deserialize_form(form), instance=userprofile) if form.is_valid(): form.save() dajax.assign("#edit_profile_nickname", "innerHTML", edit_form.cleaned_data['nickname']) dajax.remove_css_class('#profile_edit_form input', 'error') dajax.script('modal_hide()') # Hide modal show_alert(dajax, 'success', 'Profile was edited and saved') else: errors = True dajax.remove_css_class('#profile_edit_form input', 'error') for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') #show_alert(dajax, 'error', "There were errors in the form") # as it is in modal, not req else: form = EditProfileForm ( instance = userprofile ) html_content = render_to_string("users/edit_profile.html", locals(), RequestContext(request)) #dajax.remove_css_class('#id_modal', 'hide') # Show modal (already done in do_Dajax) dajax.assign("#id_modal", "innerHTML", html_content) # Populate modal return dajax.json()
def update_event(request,form): dajax = Dajax() form = UpdateForm(deserialize_form(form)) event_object = request.user.get_profile().event all_updates = Update.objects.filter(event=event_object) major_count = 0 update_count = 0 if form.is_valid(): for u in all_updates: if u.category=='Updates' and u.expired is False: update_count = update_count + 1 print update_count elif u.category=='Major Update' and u.expired is False: major_count = major_count + 1 print major_count elif update_count>4 and u.category=='Updates': dajax.alert("This event already has 4 Updates.\ Please mark one update as Expired before adding a new update") elif major_count>1 and u.category=='Major Update': dajax.alert("This event already has one Major Update.\ Please mark the Major Update as Expired before adding another one") #Write to json here else : template = loader.get_template('events/home.html') t = template.render(RequestContext(request,locals())) return dajax.json()
def show_blog(request, primkey=None): """ Shows the blog entries on the page Populates : Features Removes : Showcase, Sponsors """ dajax = Dajax() dajax.add_css_class("#showcase", "hide") dajax.add_css_class("#sponsors", "hide") html_content = "" if primkey: pass show_alert(dajax, "info", "This part has not yet been completed") else: bloglist = Thread.objects.all() # print bloglist for i in bloglist: i.description = (i.description[:100] + " ....") if len(i.description) > 100 else i.description html_content = render_to_string("blog/show.html", {"bloglist": bloglist}, RequestContext(request)) if html_content: dajax.assign("#features", "innerHTML", html_content) return dajax.json()
def roommap(request,hostel_name): dajax = Dajax() hostel_selected = AvailableRooms.objects.filter(hostel=hostel_name).order_by('room_no') html_content = render_to_string('hospi/RoomMap.html', locals(),RequestContext(request)) dajax.remove_css_class=('#id_modal','hide') dajax.assign('#id_modal',"innerHTML",html_content) return dajax.json()
def logout(request,**kwargs): dajax = Dajax() auth_logout(request) dajax.script('$.bootstrapGrowl("Successfully logged out!", {type:"success",delay:10000});' ) dajax.assign("#login_logout", "innerHTML", '<a href="#login" onclick="$(\'#login\').modal(\'show\');">Login | Sign Up </a>') dajax.add_css_class("#dashboard","hide hidden") dajax.script("window.location.hash = 'events';") return dajax.json()
def hello_world(request): """ Used for testing Dajax + Dajaxice """ dajax = Dajax() dajax.assign('#id_content','innerHTML', "Hello world !") #dajax.alert("Hello World!") return dajax.json()
def test_dajax(request): """ Simple function to rest (D)ajax(ice) """ dajax = Dajax() # To hold the json dajax.script('alert(\'hello\');'); dajax.script( '$("#container_messages").append(\'<div class="span8 offset2"><div class="alert ' + 'alert-success' + ' center"><button type="button" class="close" data-dismiss="alert"><i class="icon-close">×</i></button>' + 'This is a test script! No need to listen to me.' + ' </div></div><div class="offset2"></div>\')' ) return dajax.json()
def show_updates(request): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") if not request.user.is_authenticated(): dajax.script('$.bootstrapGrowl("Login to view your registered events", {type:"danger",delay:20000} );') return dajax.json() else: profile = request.user.get_profile() updates_list = list(Update.objects.filter(user = request.user).order_by('tag')) #TODO: order by time??: no_updates = len(updates_list) now = timezone.now() context_dict = {'updates_list':updates_list,'profile':profile,'now':now,'no_updates':no_updates,'settings':settings} html_stuff = render_to_string('dashboard/list_updates.html',context_dict,RequestContext(request)) if html_stuff: dajax.assign('#content_dash','innerHTML',html_stuff) #dajax.script('$("#event_register").modal("show");') return dajax.json()
def submit_tdp(request,teamevent_id = None,file_tdp=None): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") if teamevent_id is None or file_tdp is None: dajax.script('$.bootstrapGrowl("Invalid TDP Upload request", {type:"danger",delay:20000} );') return dajax.json() team_event =TeamEvent.objects.get(id = teamevent_id) if len(request.FILES) == 0: dajax.script('$.bootstrapGrowl("Please upload a file first!", {type:"danger",delay:20000} );') fileform = TDPFileForm(deserialize_form(file_tdp),request.FILES) try: event = teamevent.get_event() tdp = TDP(tdp=fileform,teamevent = teamevent) tdp.save() except: print return dajax.json()
def hello(request, form=None): """ Test dajax """ dajax = Dajax() dajax.alert("got from dajax"); return dajax.json()
def back(request): dajax = Dajax() dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();") no_regd = len(request.user.get_profile().get_regd_events()) reco_events = ParticipantEvent.objects.using(erp_db).filter(registrable_online=True) # reco_events = registrable_events(time = timezone.now(),user = request.user) context_dict = {'profile':request.user.get_profile(),'no_regd':no_regd,'reco_events':reco_events} html_stuff = render_to_string('dashboard/default.html',context_dict,RequestContext(request)) if html_stuff: dajax.assign('#content_dash','innerHTML',html_stuff) return dajax.json()
def contacts(request): """ Used to show table of all members participating in shaastra It creates a table for this. Renders in : right_content Refreshes : null EVERYONE : It can be seen by anyone who has signed in QUERIES TO RETRIEVE: 1. Every user's: > Name > Department > Designation > Contact > Link to profile """ dajax = Dajax() # To hold the json userprofile = request.user.get_profile() # Query dictionary will contain UserProfile and the table to be drawn query_dictionary = {} # Initialize a blank Query dictionary. query_dictionary["userprofile"] = userprofile query_dictionary["TASK_STATUSES"] = TASK_STATUSES # To search for status msg html_content = "" # ALL QUERYSETS OF TASKS FILTERED FOR THE USER MUST BE AGAIN FILTERED BY DEPARTMENT (the way I've done it for user_tasks). THIS HANDLES THE MULTIPLE IDENTITY DISORDER. # Assigning the above values # ALL all_users = ERPUser.objects.all() query_dictionary["users_info"] = [] for u in all_users: user_info = { 'iden' : u.id, 'name' : u.user.first_name + " " + u.user.last_name, 'dept' : u.get_dept_subdept(), 'desig' : u.get_position(), 'ph_mad' : u.chennai_number, 'ph_home' : u.summer_number, 'email' : u.user.email } query_dictionary['users_info'].append(user_info) html_content = render_to_string("dash/contacts.html", query_dictionary, RequestContext(request)) if html_content != "": # put html generated above into json if not null # if null, alert has already been taken care of dajax.assign('#id_content_right','innerHTML', html_content) return dajax.json()
def contact_us(request): """ Used to populate the Modal with Contact Us page """ dajax = Dajax() html_content = render_to_string("common/contact_us.html", locals(), RequestContext(request)) dajax.remove_css_class('#id_modal', 'hide') # Show modal dajax.assign("#id_modal", "innerHTML", html_content) # Populate modal #print "added" return dajax.json()
def choose_event_tdp(request, choose_form=None): dajax = Dajax() if request.method == 'POST' and choose_form !=None: form = ChooseEventForm(deserialize_form(choose_form)) if form.is_valid(): clean_form = form.clean() event_name = clean_form['event'] generic_event_instance = GenericEvent.objects.get(title=event_name) event_pk = generic_event_instance.pk tdplist = [] for tdp in TDP.objects.using(mainsite_db).filter(teamevent__event_id = event_pk): tdplist.append((tdp,tdp.teamevent.team_id)) html_content = render_to_string('events/view_tdp.html',locals(),RequestContext(request)) dajax.assign('#id_content_right','innerHTML',html_content) return dajax.json() else: form=ChooseEventForm() html_content = render_to_string('events/choose_event_tdp.html',locals(),RequestContext(request)) dajax.assign('#id_content_right','innerHTML',html_content) return dajax.json()
def test_dajax(request): """ Simple function to rest (D)ajax(ice) """ dajax = Dajax() # To hold the json dajax.script('alert(\'hello\');') dajax.script( '$("#container_messages").append(\'<div class="span8 offset2"><div class="alert ' + 'alert-success' + ' center"><button type="button" class="close" data-dismiss="alert"><i class="icon-close">×</i></button>' + 'This is a test script! No need to listen to me.' + ' </div></div><div class="offset2"></div>\')') return dajax.json()
def createteam(request,team_formset=None,event_pk=None): dajax=Dajax() teamformset=formset_factory(ShaastraIDForm) generic_event_instance = GenericEvent.objects.get(pk=event_pk) event_name = generic_event_instance.title if request.method=="POST" and team_formset != None: formset = teamformset(deserialize_form(team_formset)) print '111111111111111 %s' % formset if formset.is_valid(): userlist = [] for f in formset: print f cd = f.cleaned_data shaastraid='SHA14'+str(cd.get('shaastraID')) print shaastraid try: parti = UserProfile.objects.using(mainsite_db).get(shaastra_id=shaastraid) userlist.append(parti.user) except: if shaastraid == 'SHA14None': continue else: prof = create_junk_profile(shaastraid) userlist.append(prof.user) teamevent = TeamEvent(event_id=event_pk) teamevent.save(using='mainsite') teamevent.users = userlist teamevent.team_id = 'TEAM#'+str(event_name[:5])+'#'+str(teamevent.pk) teamevent.team_name = str(event_pk) teamevent.save(using='mainsite') show_alert(dajax,"success","Team Registered successfully.Team ID is %s" % str(teamevent.pk)) return dajax.json() else: show_alert(dajax,"error","Form is invalid") return dajax.json() else: show_alert(dajax,"error","Unexpected Error, Contact Webops") return dajax.json()
def password_reset(request, username=None, email=None): """ Generates a one-use only link for resetting password and sends to the user. """ from django.utils.http import urlsafe_base64_encode from django.core.mail import send_mail from django.contrib.sites.models import get_current_site from django.utils.encoding import force_bytes from django.contrib.auth.tokens import default_token_generator dajax = Dajax() # To hold the json if username: active_users = User.objects.filter(username__iexact=username, is_active=True) count = 0 for user in active_users: if not user.has_usable_password(): continue c = { 'email': user.email, 'site_url': settings.SITE_URL, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } subject = 'NSS-IITM Password Reset Request' email = render_to_string('emails/password_reset.html', c) ret_val = send_mail(subject, email, settings.DEFAULT_FROM_EMAIL, [user.email]) print ret_val count = count + 1 print count, "emails sent !" if count: dajax.script('alert(\'Username sent!\')') # To hold the json else: dajax.script('alert(\'Username not found!\')') # To hold the json else: dajax.script('alert(\'Please enter a username !\')') return dajax.json()