Esempio n. 1
0
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()
Esempio n. 2
0
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()
Esempio n. 3
0
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()
Esempio n. 4
0
def new_blog(request, form=None):
    """
        Handles the creation of a blog post
        - if user not logged in, give alert
        
        Populates : Features
        
        Removes : Showcase, Sponsors
    """
    dajax = Dajax()

    html_content = ""
    dajax.add_css_class("#showcase", "hide")
    dajax.add_css_class("#sponsors", "hide")

    if request.method == "POST":
        form = ThreadForm(deserialize_form(form))
        print form
        if form.is_valid():  # check validity
            form.save()
            show_alert(dajax, "success", "Your post has been saved !")
        else:  # form was not valid, show errors
            dajax.remove_css_class("#form_new_blog_post input", "error")
            for error in form.errors:  # tell which parts had errors
                dajax.add_css_class("#id_%s" % error, "error")
            print [error for error in form.errors]
            show_alert(dajax, "error", "There were some errors : please rectify them")  # show alert
Esempio n. 5
0
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()
Esempio n. 6
0
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()
Esempio n. 7
0
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()
Esempio n. 8
0
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()
Esempio n. 9
0
def display_task(request, primkey, comments_field=None):
    """
        Displays a task to viewers with a commet field
        It handles the displaying of all tasks : intra and cross
        
        The post method handles the receiving of a submitted comment and saves it
        
        Renders in : modal
        Refreshes : if new comment added, refreshed content of modal
    """
    # TODO: Redirect people who aren't allowd to view this task. 
    # Add edit and delete buttons for cores and supercoords
    # Display ALL details in the template - template needs work.
    print primkey
    dajax = Dajax()
    html_content = ""
    primkey = int(primkey)
    
    # Save comment if new comment given
    
    # Get Task + comments and populate
    try:
        task = Task.objects.get(pk = primkey)
        task_statuses = TASK_STATUSES
        print "task"
        if request.method == 'POST' and comments_field != None: # Add new comment if necessary
            if comments_field == "":
                dajax.add_css_class("#comments_field", "error")
            else :
                task_comment = Comment()
                task_comment.task = Task.objects.filter(id = task.id)[0]
                task_comment.author = request.user
                task_comment.comment_string = comments_field
                task_comment.time_stamp = datetime.datetime.now()
                task_comment.save()
        print "check comment"        
        if ( comments_field != "" and comments_field != None ) or request.method == 'GET': 
            print "true"
            # i.e. if "Submit Comment" was pressed, and comment was given OR GET ... need to refresh
            comments = Comment.objects.filter(task = task)
            html_content = render_to_string('tasks/display.html', locals(), RequestContext(request))
            print html_content
            dajax.remove_css_class('#id_modal', 'hide') # Show modal
            dajax.assign("#id_modal", "innerHTML", html_content) # Populate modal
        print "done"
    except:
        show_alert(dajax, "error", "The task was not found")
        html_content = ""
    
    return dajax.json()
Esempio n. 10
0
def delete_task(request, primkey):
    """
        This function handles deleting any task
        CORES : (ONLY)
            Only they can delete tasks.
        
        Renders in : alert
        Refreshes : right_content
    """
    dajax = Dajax()
    try:
        task = Task.objects.get(pk = primkey)
        subj = task.subject
        task.delete()
        show_alert(dajax, "success", "Task " + subj + " was deleted !") # Shows alert
        dajax.script("modal_hide()") # This refreshes the current tab to update what changes need to be made
    except:
        show_alert(dajax, "error", "That task does not exist !") # Shows alert
        
    return dajax.json()
Esempio n. 11
0
def contactus(request, form = None):
    """
        Handles the "contact us" form on the home page
    """
    dajax = Dajax() # to hold dajax-json
    
    if request.method == 'POST':
        form = ContactRequestsForm(deserialize_form(form))
        print form
        if form.is_valid(): # check validity
            form.save()
            # @Ali: clear the form after saving it, the below command didnt do it, and make the send button pseud
            #form = ContactRequestsForm()
            show_alert(dajax, "success", "Your message has been submitted. We will get back to you shortly")
        else: # form was not valid, show errors
            dajax.remove_css_class('#form_footer_contactus input', 'error')
            for error in form.errors: # tell which parts had errors
                dajax.add_css_class('#id_%s' % error, 'error')
            print [error for error in form.errors]
            show_alert(dajax, 'error', "There were some errors : please rectify them") # show alert
Esempio n. 12
0
def add_update(request,event_pk=None,update_form=None,update_pk=None):
    dajax = Dajax()
    if request.method == 'POST' and update_form != None:
        form = UpdateForm(deserialize_form(update_form))
        generic_event_instance = GenericEvent.objects.get(pk=event_pk)
        all_updates = Update.objects.filter(event=generic_event_instance)
        update_count = 0
        major_count = 0
        if update_pk:
            pass
        else:
            for u in all_updates:
                if (update_count>=3) and (u.category=='Updates'):
                    show_alert(dajax,'error',"This event already has 4 Updates.\
                                Please mark one update as Expired before adding a new update")
                    return dajax.json()
                elif (major_count>=1) and (u.category=='Major Update'):
                    show_alert(dajax,'error',"This event already has one Major Update.\
                                Please mark the Major Update as Expired before adding another one")
                    return dajax.json()
                elif u.category=='Updates':
                    if u.expired is False:
                        update_count = update_count + 1
                elif u.category=='Major Update': 
                    if u.expired is False:
                        major_count = major_count + 1
        if form.is_valid():
            try:
                form.save(event_inst = generic_event_instance,update_pk=update_pk)
            except EditError as error:
                show_alert(dajax,"error",error.value)
                return dajax.json()
        else:
            show_alert(dajax,"error","Some information seems to be missing, please fill the form again")
            return dajax.json()
        all_updates = Update.objects.filter(event=generic_event_instance)
        html_content = render_to_string('events/add_update.html',locals(),RequestContext(request))
        dajax.assign("#id_content_right","innerHTML",html_content)
        return dajax.json()
    else:
        if update_pk:
            update_instance = Update.objects.get(pk=update_pk)
            form = UpdateForm(instance = update_instance)
        else:
            form = UpdateForm()
        generic_event_instance = GenericEvent.objects.get(pk=event_pk)
        all_updates = Update.objects.filter(event=generic_event_instance)
        html_content = render_to_string('events/add_update.html',locals(),RequestContext(request))
        dajax.assign('#id_content_right','innerHTML',html_content)
        return dajax.json()
Esempio n. 13
0
def checkout(request,shaastra_form=None):
    dajax = Dajax()
    if request.method=='POST' and shaastra_form != None:
        form = ShaastraIDForm(deserialize_form(shaastra_form))
        if form.is_valid():
            cleaned_form = form.cleaned_data
            print cleaned_form
            shaastraid = 'SHA14'+cleaned_form['shaastraID']
            print shaastraid
            try:
                participant = UserProfile.objects.using(mainsite_db).get(shaastra_id = shaastraid)
            except:
                show_alert(dajax,"error","User with this Shaastra ID does not exist")
                return dajax.json()
            try:
                checkedin = IndividualCheckIn.objects.get(shaastra_ID=shaastraid)
                if checkedin.check_out_date:
                    show_alert(dajax,"error","Participant has already checked out")
                    return dajax.json()
                else:
                    checkedin.check_out_date = datetime.now()
                    checkedin.check_out_control_room = checkedin.check_in_control_room
                    checkedin.save()
                    room = checkedin.room
                    room.max_number += 1
                    room.save()
                    show_alert(dajax,"success","Participant checked out successfully")
                    return dajax.json()
            except:
                show_alert(dajax,"error","Participant never checked in !")
                return dajax.json()
        else:
            show_alert(dajax,"error","An unexpected error has occured. Contact Webops ASAP")
            return dajax.json()
    else:
        form=ShaastraIDForm()
        html_content = render_to_string('hospi/Checkout.html',locals(),RequestContext(request))
        dajax.assign('#tab4',"innerHTML",html_content)
        return dajax.json()
Esempio n. 14
0
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()
Esempio n. 15
0
def checkin(request,indi_form=None):
    dajax = Dajax()
    if request.method == 'POST' and indi_form != None:
        form = ShaastraIDForm(deserialize_form(indi_form))
        if form.is_valid():
            cleaned_form=form.cleaned_data
            shaastraid = 'SHA14'+cleaned_form['shaastraID']
            try:
                participant = UserProfile.objects.using(mainsite_db).get(shaastra_id = shaastraid) #So participant in the database can be pre-reg or junk
            except:
                new_form = RegistrationForm(initial={'shaastra_id':shaastraid})
                college_form = CollegeForm()
                html_content = render_to_string('hospi/Register.html',locals(),RequestContext(request))
                dajax.assign('#tab3',"innerHTML",html_content)
                return dajax.json()
            try:
                checkedin = IndividualCheckIn.objects.get(shaastra_ID=shaastraid)
                room = checkedin.room
                checkedindate = checkedin.check_in_date
                checkedoutdate = checkedin.check_out_date
                if checkoutdate:
                    show_alert(dajax,"info","Participant was checked-in into" + str(room) + ".He has already checked-out on" + str(checkoutdate))
                    return dajax.json()
                else:
                    show_alert(dajax,"info","Participant is already checked-in into" + str(room))
                    return dajax.json()
            except:
                if is_junk(shaastraid):
                    participant.user.is_staff = False
                    new_form = RegistrationForm(initial={'shaastra_id':shaastraid})
                    college_form = CollegeForm()
                    html_content = render_to_string('hospi/Register.html',locals(),RequestContext(request))
                    dajax.assign('#tab3',"innerHTML",html_content)
                    return dajax.json()
                else:
                    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()
    else:
        form = ShaastraIDForm()
        html_content = render_to_string('hospi/Checkin_indi.html',locals(),RequestContext(request))
        dajax.assign('#tab3',"innerHTML",html_content)
        return dajax.json()
Esempio n. 16
0
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()
Esempio n. 17
0
def remove(request,rem_form=None):
    dajax=Dajax()
    if request.method=='POST' and rem_form != None:
        form = RemoveRoom(deserialize_form(rem_form))
        if form.is_valid():
            cleaned_form=form.cleaned_data
            room_num = cleaned_form['room_no']
            hostel = cleaned_form['hostel']
            try:
                exist_room = AvailableRooms.objects.get(room_no=room_num,hostel=hostel)
                exist_room.delete()
                show_alert(dajax,"success","Room deleted successfully")
                return dajax.json()
            except:
                show_alert(dajax,"error","This room has not been added")
                return dajax.json()
        else:
            show_alert(dajax,"error","Form is not valid")
            return dajax.json()
    else:
        form=RemoveRoom()
        html_content = render_to_string('hospi/Remove.html',locals(),RequestContext(request))
        dajax.assign('#tab5',"innerHTML",html_content)
        return dajax.json()
Esempio n. 18
0
def show_event_erp(request, event_name=None, event_pk=None):
    """
        This function gets the data from the json file and gives it to 
        the template to show it in nice html content. This template is for ERP.
        Mainsite may require another template.
        
        You can query based on name or pk.
        
        An existing event can be either audience or participant event. The correct event is displayed.
    """
    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_name = generic_event_instance.title
        event_type = generic_event_instance.event_type
        if event_type=='Participant':
            event_instance = ParticipantEvent.objects.get(pk=event_pk)
        elif event_type=='Audience':
            event_instance = AudienceEvent.objects.get(pk=event_pk)
        else: #if no event type -- show error
            show_alert(dajax, "error", "There is some error with this event. Contact the WebOps team.")
            return dajax.json()
        tab_list = Tab.objects.filter(event=event_instance) # for providing the list of tabs to erp_tabs.html
    else:
        show_alert(dajax, "error", "This event has not been created on the site. Contact WebOps team.")
        return dajax.json()
    
    event_json_filepath = get_json_file_path(str(event_instance.pk) + '_' + event_instance.title + '.json')
    #print event_json_filepath
    
    if not os.path.exists(event_json_filepath): # No file found
        # if the event exists in db but no json file present, then create a json file with the event and its tabs' details
        if event_instance:
            event_dict = model_to_dict(event_instance)
            if event_type=='Participant':
                form = ParticipantEventDetailsForm(event_dict, instance=event_instance)

            elif event_type=='Audience':
                form = AudienceEventDetailsForm(event_dict, instance=event_instance)
            #form = EventDetailsForm(event_dict, instance=event_instance)
            if form.is_valid():
                form.save()
            for tab in tab_list:
                tab_dict = model_to_dict(tab)
                #print tab_dict
                tab_form = TabDetailsForm(tab_dict, instance=tab)
                if tab_form.is_valid():
                    tab_form.save(event_inst = event_instance)
        else: # return an empty page and let the user add event details
            show_alert(dajax, "error", "Event details not found. Click Edit Event Details button to add details to this event.")
            html_content = render_to_string('events/erp_tabs.html', locals(), RequestContext(request))
            dajax.assign("#id_content_right", "innerHTML", html_content)
            return dajax.json()
    with open(event_json_filepath) as f:
        json_dict = json.dumps(json.load(f), sort_keys=False, indent=4) # This is a json object
        html_content = render_to_string('events/erp_tabs.html', locals(), RequestContext(request))
        f.close()
    
    # Now that json data is in json_dict : populate in a template and give
    if html_content:
        dajax.assign("#id_content_right", "innerHTML", html_content) # Populate content
        #dajax.script("display_event_erp($('#json_dict_content').val());") # run the function to populate the json content
        
    return dajax.json()
Esempio n. 19
0
def edit_event(request, event_name=None, event_pk=None, edit_form=None):
    """
        This function renders the "edit event" page for Event coords
        args : 
            event_name - The name of the event which needs to be edited
            event_pk - The pk of the event which needs to be edited
            edit_Form - The edited form in post requests
        
        Check before savin
            - check if name changed, if yes : change file name
            
        An existing event can be either audience or participant event.
        If new event is being created, a GenericEventForm is displayed, and it can be saved with event type as audience or participant event.
    """
    dajax = Dajax()
    html_content = ""
    event_query = None
    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_pk:
        event_query = GenericEvent.objects.filter(pk=event_pk)
    elif event_name:
        event_query = GenericEvent.objects.filter(title=event_name)

    if event_query: # get event details and tab details
        generic_event_instance = event_query[0]
        event_pk = generic_event_instance.pk
        event_type = generic_event_instance.event_type
        if event_type=='Participant':
            event_instance = ParticipantEvent.objects.get(pk=event_pk)
        elif event_type=='Audience':
            event_instance = AudienceEvent.objects.get(pk=event_pk)
        else: #if no event type -- show error
            show_alert(dajax, "error", "There is some error with this event. Contact the WebOps team.")
            return dajax.json()

    if request.method == 'POST' and edit_form != None:
        if event_instance:
            if event_type=='Participant':
                form = ParticipantEventDetailsForm(deserialize_form(edit_form), instance = event_instance)
            elif event_type=='Audience':
                form = AudienceEventDetailsForm(deserialize_form(edit_form), instance = event_instance)
            #form = EventDetailsForm(deserialize_form(edit_form), instance = event_instance)
            event_name_old = event_instance.title
        else:
            form = GenericEventDetailsForm(deserialize_form(edit_form))

        if form.is_valid(): # Save form and json
            clean_form = form.clean()
            # Handles the form and sql
            try:
                form.save()
            except EditError as error:
                show_alert(dajax, "error", error.value)
                return dajax.json()
            
            # check if event name has changed, change the event - tab title if yes.
            if event_instance:
                event_name_new = clean_form['title']
                if event_name_new != event_name_old: # Change event - tab title
                    dajax.assign("#a_event_" + str(event_instance.pk), "innerHTML", event_name_new)
            
            dajax.remove_css_class('#id_form input', 'error')
            show_alert(dajax, "success", "Event edited successfully")
        else:
            error_string = "<br />"
            dajax.remove_css_class('#id_form input', 'error')
            for error in form.errors:
                error_string += error[0].upper() + error[1:] + ": " + form.errors[error][0] + "<br />"
                dajax.add_css_class('input#id_%s' % error, 'error')

            if event_instance:
                if event_type=='Participant':
                    form = ParticipantEventDetailsForm()
                elif event_type=='Audience':
                    form = AudienceEventDetailsForm()
            else:
                form = GenericEventDetailsForm()
            
            show_alert(dajax, "error", error_string)
            #html_content = render_to_string('events/edit_event.html', locals(), RequestContext(request)) # show edit form again
    else:
        if event_instance:
            if event_type=='Participant':
                form = ParticipantEventDetailsForm(instance = event_instance)
            elif event_type=='Audience':
                form = AudienceEventDetailsForm(instance = event_instance)
            #form = EventDetailsForm(instance = event_instance)
        else:
            form = GenericEventDetailsForm()
        
        context_dict = {'model_instance' : event_instance, 'type' : 'event', 'form' : form}
        html_content = render_to_string('events/edit_form.html', context_dict, RequestContext(request))

    if html_content:
        if event_instance:
            dajax.assign("#event_" + str(event_instance.pk), "innerHTML", html_content) # Populate content
        else:
            dajax.assign("#event_new", "innerHTML", html_content) # Populate content for new event

    return dajax.json()
Esempio n. 20
0
def new_intra_task(request, serializedform=None, primkey=None):
    """
        Serves and processes a new intradepartmental task.
         - if processing error, shows errors on same form
         - if no error, shows success alert
        
        CORES and SUPERS :
            Have access to edit and add tasks
            
        Arguments :
            serializedform - in post request, the form is sent
            primkey - prinkey of parent task (if any)
        
        Fields entered by user:
            '******', 'subject', 'description', 'taskforce'
        
        Fields automatically taken care of by model/model save function override:
            'taskcreator', 'datecreated', 'datelastmodified', 'depthlevel', 'parenttask'
        
        Fields taken care of by the view:
            'targetsubdepts', 'origindept', 'targetdept', 'isxdepartmental', 'taskstatus'
    """
    dajax = Dajax()
    
    print ("Primkey: %s" % primkey)

    # Check parent task and create parent-string
    if primkey:
        # Need to figure out the try, except block here
        parenttask = Task.objects.get(pk=primkey)
        parentlabel = "\nParent task: " + parenttask.subject
    else:
        parentlabel = "\nThis is a top level task."
        parenttask = None
    
    # Get basic data
    id_form = "new_task"
    userprofile = request.user.get_profile()
    department = userprofile.dept
    title = "Add Intradepartmental Task"
    info = parentlabel
    
    if request.method == 'POST' and serializedform != None:
        form = IntraTaskForm(department, deserialize_form(serializedform)) # get form
        if form.is_valid(): # check validity
            newTask = form.save(commit=False)
            
            #Set the origin & target departments & approve the task.        
            newTask.origindept = userprofile.dept
            newTask.targetdept = userprofile.dept
            newTask.taskcreator = userprofile
            newTask.taskstatus = 'O'
            newTask.parenttask = parenttask
            
            #For many to many relationships to be created, the object MUST first exist in the database.
            newTask.save()
            #UNCOMMENT THE BELOW LINE IF MANYTOMANY DATA IS BEING SAVED DIRECTLY FROM THE FORM
            #form.save_m2m()
                    
            #Get the TaskForce from the form
            cores = form.cleaned_data['cores']
            coords = form.cleaned_data['coords']
            supercoords = form.cleaned_data['supercoords']
            
            #Set the TaskForce for the Task
            for user in coords: 
                newTask.taskforce.add(user)
            for user in supercoords: 
                newTask.taskforce.add(user)
            for user in cores: 
                newTask.taskforce.add(user)
        
            newTask.save() # task saved
            
            dajax.remove_css_class('#form_' + str(id_form) + ' input', 'error') # remove earlier errors mentioned
            show_alert(dajax, 'success', "Task saved successfully") # show alert
        else: # some errors found 
            errors = True
            dajax.remove_css_class('#form_' + str(id_form) + ' input', 'error')
            for error in form.errors: # tell which parts had errors
                dajax.add_css_class('#id_%s' % error, 'error')
            print [error for error in form.errors]
            show_alert(dajax, 'error', "There were some errors : please rectify them") # show alert
Esempio n. 21
0
def upgrade_task(request, primkey=None, direc=1):
    """
        Handles the upgrade task requests.
        CORE :
            Can upgrade from unapproved upto completed
            Can downgrade from completed to unapproved
        SUPERCOORD/COORD :
            Can upgrade from approved, ongoing upto Reported complete
            
        Renders in: alert
    """
    dajax = Dajax()
    direc = int(direc)
    
    userprofile = request.user.get_profile()
    upgradeable_statuses = [] #  A List containing all task_statuses to allow current to upgrade from and to (in order)
    if userprofile.is_coord():
        upgradeable_statuses = [
            TASK_STATUSES[1], # Approved and Ongoing
            TASK_STATUSES[2], # Approved, nearly done
            TASK_STATUSES[3], # Reported Complete
        ]
    elif userprofile.is_supercoord():
        upgradeable_statuses = [
            TASK_STATUSES[1], # Approved and Ongoing
            TASK_STATUSES[2], # Approved, nearly done
            TASK_STATUSES[3], # Reported Complete
        ]
    elif userprofile.is_core():
        upgradeable_statuses = TASK_STATUSES # All task statuses
    task = Task.objects.get(pk=int(primkey))
    flag_i_stat = 0;
    if task.taskstatus == 'C':
        """
            Taskstatus is maximum, don't do anything, give a warning
        """
        flag_i_stat = 2
        show_alert(dajax, 'warning', 'This Task is already completed.')
    elif direc == -1 and userprofile.is_core():
        """
            Only for cores
            
            Down grade the task. Go through the tuple elements by number,
            And give the taskstatus th value for i-2 (if that status exists)
            Give alert depending on what happened
        """
        for i_stat in range(len(upgradeable_statuses)): # This should be the whole list[0:x], else it won't work
            if flag_i_stat == 1:
                if i_stat >= 2: # if it is smaller, i cannot go negative, so leave as is
                    task.taskstatus = upgradeable_statuses[i_stat-2][0] # Set new task status
                    flag_i_stat = 2
                    task.save()
                    dajax.script("modal_hide()") # Refreshes the current tab
                    stat_msg = ""
                    for i_ in TASK_STATUSES:
                        if i_[0] == task.taskstatus:
                            stat_msg = i_[1]
                    show_alert(dajax, 'success', 'Task ' + task.subject + ' rejected to ' + stat_msg) # Gives success message
                else: # give error msg ?
                    dajax.script("alert('what to do if task is unapproved and rejected?')")
                break
            elif upgradeable_statuses[i_stat][0] == task.taskstatus:
                flag_i_stat = 1
    else:
        """
            For everyone
            
            Upgrade the task. Go through the tuple elements based on position
            And give the taskstatus the value after the current (if exists)
            Give alert depending on what happened
        """
        for i_stat in upgradeable_statuses:
            if flag_i_stat == 1:
                task.taskstatus = i_stat[0] # Set new task status
                flag_i_stat = 2
                task.save()
                dajax.script("modal_hide()") # Refreshes the current tab
                stat_msg = ""
                for i_ in TASK_STATUSES:
                    if i_[0] == task.taskstatus:
                        stat_msg = i_[1]
                show_alert(dajax, 'success', 'Task ' + task.subject + ' upgraded to ' + stat_msg) # Gives success message\
                break
            elif i_stat[0] == task.taskstatus:
                flag_i_stat = 1 # Next loop is what I need to set
    
    if flag_i_stat != 2: # New status was never set ... i.e. Not in upgradeable_statuses
        show_alert(dajax, 'error', 'Task was not upgraded. You cannot upgrade this task.') # Gives error message
        
    return dajax.json()
Esempio n. 22
0
def task_table(request, page):
    """
        Used to show table of subdepartment tasks using Dajax(ice)
        It handles all tables (personal/you, subdept, dept, pending, cross) of all users (coord, supercoord, core)
        
        Renders in : right_content
        Refreshes : null
        
        CORES :
            Personal/You
            Department
            Pending
            CrossTasks
        SUPERCOORD :
            Personal/You
            Department
        COORD :
            Personal/You
            SubDepartment
            
        QUERIES TO RETRIEVE:
            1.  The user's tasks.
            2.  Tasks assigned to the department
            3.  Tasks assigned to the subdepartment
            4.  The Crosstasks created by the department
            5.  Tasks pending approval
            6.  ?Crosstasks _to_ the department?

    """
    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
    if page == "table_you":
        query_dictionary["user_tasks"] = userprofile.task_set.filter(targetdept=userprofile.dept).all()
        if userprofile.is_coord():
            html_content = render_to_string("dash/task_tables/coord_you.html", query_dictionary, RequestContext(request))
        elif userprofile.is_supercoord():
            html_content = render_to_string("dash/task_tables/supercoord_you.html", query_dictionary, RequestContext(request))
        elif userprofile.is_core():
            html_content = render_to_string("dash/task_tables/core_you.html", query_dictionary, RequestContext(request))
    
    # COORD ONLY
    elif page == "table_subdept" and userprofile.is_coord():
        #The attribute userprofile.subdept is present only if he's a coord
        query_dictionary["subdept_tasks"] = userprofile.subdept.task_set.exclude(taskstatus='U')
        html_content = render_to_string("dash/task_tables/coord_subdept.html", query_dictionary, RequestContext(request))
        
    # SUPERCOORD ONLY
    elif page == "table_cross" and userprofile.is_supercoord():
        query_dictionary["dept_todo_crosstasks"] = userprofile.dept.todo_task_set.filter(isxdepartmental=True).exclude(taskstatus='U') #Remove if necessary.
        html_content = render_to_string("dash/task_tables/supercoord_cross.html", query_dictionary, RequestContext(request))
    elif page == "table_dept" and userprofile.is_supercoord():
        query_dictionary["dept_tasks"] = userprofile.dept.todo_task_set.exclude(taskstatus='U')
        html_content = render_to_string("dash/task_tables/supercoord_dept.html", query_dictionary, RequestContext(request))
      
    # CORE ONLY
    elif page == "table_pending" and userprofile.is_core():
        query_dictionary["approval_pending_tasks"] = userprofile.dept.todo_task_set.filter(Q(taskstatus='R') | Q(taskstatus='U')) # Reported Completed tasks
        #query_dictionary["approval_pending_tasks"] += userprofile.dept.todo_task_set.filter(taskstatus='U') # Unapproved tasks
        html_content = render_to_string("dash/task_tables/core_pending.html", query_dictionary, RequestContext(request))
    elif page == "table_cross" and userprofile.is_core():
        query_dictionary["dept_created_crosstasks"] = userprofile.dept.created_task_set.filter(isxdepartmental=True)
        html_content = render_to_string("dash/task_tables/core_cross.html", query_dictionary, RequestContext(request))
    elif page == "table_dept" and userprofile.is_core():
        query_dictionary["dept_tasks"] = userprofile.dept.todo_task_set.exclude(taskstatus='U')
        html_content = render_to_string("dash/task_tables/core_dept.html", query_dictionary, RequestContext(request))
    
    # Weird case
    else:
        show_alert(dajax, 'error','Could not find the requested table. Contact WebOps Team.')
        
    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()
Esempio n. 23
0
def new_cross_task(request, serializedform=None, primkey=None):
    """
        Serves and processes a new intradepartmental task.
         - if processing error, shows errors on same form
         - if no error, shows success alert
        
        CORES: (ONLY)
            Have access to edit and add tasks
            
        Arguments :
            serializedform - in post request, the form is sent
            primkey - prinkey of parent task (if any)
        
        Fields entered by user:
            '******', 'subject', 'description', 'parenttask', 'targetsubdepts'
        
        Fields automatically taken care of by model/model save function override:
            'taskcreator', 'datecreated', 'datelastmodified', 'depthlevel'
        
        Fields taken care of by the view:
            'origindept', 'targetdept', 'isxdepartmental', 'taskstatus' 
            
        Fields that are unset:
             'taskforce'
    """
    dajax = Dajax()
    
    # Check parenttask and create parent-string
    if primkey:
        parenttask = Task.objects.get(pk=primkey)
        parentlabel = "\nParent task: " + parenttask.subject
    else:
        parentlabel = "\nThis is a top level task."
        parenttask = None
    
    # Add some more basic info
    title = "Add Cross-departmental Task."
    info = "Subject to approval of the target department's core." + parentlabel
    userprofile = request.user.get_profile()
    department = userprofile.dept
    id_form = "new_cross_task"
    
    if request.method == 'POST' and serializedform != None:
        form = CrossTaskForm(department, deserialize_form(serializedform))
        if form.is_valid():
            #Create a task object without writing to the database
            newTask = form.save(commit=False)
            
            #Get selected subdepartment from form and set targetdepartment
            #There's only one object in the form field - the loop is only going to run once.
            for subdept in form.cleaned_data['targetsubdepts']:
                newTask.targetdept = subdept.dept
            
            #Set these variables - Unapproved X-Departmental task
            newTask.taskcreator = userprofile
            newTask.isxdepartmental = True
            newTask.taskstatus = 'U'
            if primkey:
                newTask.parenttask = parenttask
      
            #Set the origin & target departments.        
            newTask.origindept = userprofile.dept
            
            #For many to many relationships to be created, the object MUST first exist in the database
            #Saves newTask and also saves the ManyToMany Data
            newTask.save()
            form.save_m2m() # Form saved
            
            dajax.remove_css_class('#form_' + str(id_form) + ' input', 'error') # remove earlier errors mentioned
            show_alert(dajax, 'success', "Task saved successfully") # show alert
        else: # some errors found 
            errors = True
            dajax.remove_css_class('#form_' + str(id_form) + ' input', 'error')
            for error in form.errors: # tell which parts had errors
                dajax.add_css_class('#id_%s' % error, 'error')
            print [error for error in form.errors]
            show_alert(dajax, 'error', "There were some errors : please rectify them") # show alert
Esempio n. 24
0
def team_checkout(request,team_form=None):
    dajax=Dajax()
    if request.method == 'POST' and team_form != None:
        form = TeamCheckoutForm(deserialize_form(team_form))
        if form.is_valid():
            cleaned_form = form.cleaned_data
            check_out_control_room = cleaned_form['check_out_control_room']
            event_name = cleaned_form['event']
            actual_name = event_name[:5]
            team_id_num = cleaned_form['team_id_num']
            team_id = 'TEAM#'+str(actual_name)+'#'+str(team_id_num)
            team_instance = TeamEvent.objects.using(mainsite_db).get(team_id=team_id)
            if check_out_control_room == 'Godav':
                users_in_team = team_instance.users.all()
                for user_ex in users_in_team:
                    shaastraid = user_ex.userprofile_set.all()[0].shaastra_id
                    try:
                        checkedin = IndividualCheckIn.objects.get(shaastra_ID=shaastraid)
                        if checkedin.check_out_date:
                            show_alert(dajax,"error","Participant has already checked out")
                            return dajax.json()
                        else:
                            checkedin.check_out_date = datetime.now()
                            checkedin.check_out_control_room = checkedin.check_in_control_room
                            room = checkedin.room
                            room.max_number += 1
                            room.save()
                            checkedin.save()
                    except:
                        show_alert(dajax,"error","Not checked in")
                        return dajax.json()
                show_alert(dajax,"success","Team Checked out")
                return dajax.json()

            else: 
                users_in_team = team_instance.users.all()
                for user_ex in users_in_team:
                    shaastraid = user_ex.userprofile_set.all()[0].shaastra_id
                    try:
                        checkedin = IndividualCheckIn.objects.get(shaastra_id=shaastraid)
                        if checkedin.check_out_date:
                            show_alert(dajax,"error","Participant has already checked out")
                            return dajax.json()
                        else:
                            checkedin.check_out_date = datetime.now()
                            checkedin.check_out_control_room = checkedin.check_in_control_room
                            checkedin.save()
                            room = checkedin.room
                            room.max_number += 1
                            room.save()
                            show_alert(dajax,"success","Checked out successfully")
                    except:
                        show_alert(dajax,"error","Not checked in")
                        return dajax.json()
                return dajax.json()
        else:
            show_alert(dajax,"error","Form is invalid")
            return dajax.json()

    else:
        form = TeamCheckoutForm()
        html_content = render_to_string('hospi/TeamCheckout.html',locals(),RequestContext(request))
        dajax.assign('#tab8',"innerHTML",html_content)
        return dajax.json()
Esempio n. 25
0
def edit_tab(request, tab_pk=None, event_pk=None, edit_form=None, delete_tab=None):
    """
        This function renders the "edit event" page for Event coords
        args :
            tab_pk - the pk of the tab being edited
            form - the form sent in post request
            event_pk - pk of event the tab belongs to. must exist.
            delete_tab - indicates whether to delete the tab or not
            
        Check before savin
            - check if name changed, if yes : change file name
            
        In the form :
            event - got from event_pk
            title, desc, pref - got from form
            
    """
    dajax = Dajax()
    html_content = ""
    new_tab_created = False
    if tab_pk:
        tab_instance = Tab.objects.get(pk=tab_pk)
    else:
        tab_instance = None
    
    if event_pk:
        generic_event_instance = GenericEvent.objects.get(pk=event_pk)
        event_type = generic_event_instance.event_type
        if event_type=='Participant':
            event_instance = ParticipantEvent.objects.get(pk=event_pk)
        elif event_type=='Audience':
            event_instance = AudienceEvent.objects.get(pk=event_pk)
        else:
            show_alert(dajax, "error", "There is some error with this event. Contact the WebOps team.")
            return dajax.json()
    else:
        show_alert(dajax, "error", "There is some problem with this tab. Contact WebOps team.")
        return dajax.json()
        
    if request.method == 'POST' and edit_form != None:
        if tab_instance: # Old tab being edited
            form = TabDetailsForm(deserialize_form(edit_form), instance = tab_instance)
            tab_name_old = tab_instance.title
        else: # New tab
            form = TabDetailsForm(deserialize_form(edit_form))
            new_tab_created = True

        if form.is_valid(): # Save form and json
            clean_form = form.clean()
            # Handles the form and sql
            try:
                form.save(event_inst = event_instance)
            except EditError as error:
                show_alert(dajax, "error", error.value)
                return dajax.json()
                        
            # change tab name if it has changed
            if tab_instance:
                tab_name_new = clean_form['title']
                if tab_name_new != tab_name_old: # Change tab title
                    dajax.assign("#a_tab_" + str(tab_instance.pk), "innerHTML", tab_name_new)
            
            if new_tab_created:
                # Note : need to make this better. Currently, it'll refresh the whole left content. It's better to add what's required only...
                dajax.script("$('#list_eventpage_eventinfo').find('a').click();")
                
            dajax.remove_css_class('#id_form input', 'error')
            show_alert(dajax, "success", "Tab edited successfully")
        else:
            error_string = "<br />"
            dajax.remove_css_class('#id_form input', 'error')
            for error in form.errors:
                error_string += error[0].upper() + error[1:] + ": " + form.errors[error][0] + "<br />"
                dajax.add_css_class('#id_%s' % error, 'error')

            form = TabDetailsForm()
            show_alert(dajax, "error", error_string)
            #html_content = render_to_string('events/edit_tab.html', locals(), RequestContext(request)) # show edit form again
    elif request.method == 'POST' and delete_tab == 'delete':
        if tab_instance:
            try:
                tab_instance.delete()
            except EditError as error:
                show_alert(dajax, "error", error.value)
                return dajax.json()
            # Note : need to make this better. Currently, it'll refresh the whole left content. It's better to add what's required only...
            show_alert(dajax, "success", "Tab deleted successfully")
            dajax.script("$('#list_eventpage_eventinfo').find('a').click();")
        else:
            show_alert(dajax, "error", "There is some problem with deleting this tab. Contact the WebOps Team.")
            return dajax.json()
    else:
        if tab_instance:
            form = TabDetailsForm(instance = tab_instance)
        else:
            form = TabDetailsForm()
        
        context_dict = {'model_instance' : tab_instance, 'type' : 'tab', 'tab_event_pk': event_pk, 'form' : form}
        html_content = render_to_string('events/edit_form.html', context_dict, RequestContext(request))

    if html_content :
        if tab_instance:
            dajax.assign("#tab_" + str(tab_instance.pk), "innerHTML", html_content) # Populate content
        else:
            dajax.assign("#tab_new", "innerHTML", html_content) # Populate content
        dajax.script("display_editor('id_text');") # give id of the form textarea to display_editor function
    return dajax.json()
Esempio n. 26
0
def team(request,team_form=None):
    dajax=Dajax()
    if request.method=="POST" and team_form != None:
        form = TeamCheckinForm(deserialize_form(team_form))
        if form.is_valid():
            cleaned_form=form.cleaned_data
            check_in_control_room = cleaned_form['check_in_control_room']
            event_name = cleaned_form['event']
            generic_event_instance = GenericEvent.objects.get(title=event_name)
            event_pk = generic_event_instance.pk
            actual_name = event_name[:5]
            team_id_num = cleaned_form['team_id_num']
            team_id = 'TEAM#'+str(actual_name)+'#'+str(cleaned_form['team_id_num'])
            print team_id
            team_instance = TeamEvent.objects.using(mainsite_db).get(team_id=team_id)
            if check_in_control_room=='Godav':
                userlist = []
                checkedlist = []
                shalist=[]
                checkedin_shalist = []
                users_in_team = team_instance.users.all()
                for user_ex in users_in_team:
                    shaastraid = user_ex.userprofile_set.all()[0].shaastra_id
                    try:
                        checkedin_already = IndividualCheckIn.objects.get(shaastra_ID=shaastraid)
                        if user_ex.userprofile_set.all()[0].gender == 'M':
                            checkedlist.append(user_ex.userprofile_set.all()[0])
                            checkedin_shalist.append(user_ex.userprofile_set.all()[0].shaastra_id)
                        else:
                            pass
                    except:
                        if user_ex.userprofile_set.all()[0].gender == 'M':
                            userlist.append(user_ex.userprofile_set.all()[0])
                            shalist.append(user_ex.userprofile_set.all()[0].shaastra_id)
                tcheckinformset = modelformset_factory(IndividualCheckIn,form=IndividualForm,extra=len(userlist))
                formset = tcheckinformset(queryset=IndividualCheckIn.objects.filter(shaastra_ID__in = checkedin_shalist),initial=[{'shaastra_ID':sid,'check_in_control_room':'Godav','check_out_control_room':'Godav'} for sid in shalist])
                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/TeamDisplay.html',locals(),RequestContext(request))
                dajax.assign('#tab7',"innerHTML",html_content)
                return dajax.json()
            else:
                userlist = []
                shalist=[]
                checkedlist =[]
                checkedin_shalist =[]
                users_in_team = team_instance.users.all()
                for user_ex in users_in_team:
                    shaastraid = user_ex.userprofile_set.all()[0].shaastra_id
                    try:
                        checkedin_already = IndividualCheckIn.objects.get(shaastra_ID=shaastraid)
                        if user_ex.usreprofile_set.all()[0].gender == 'F':
                            checkedlist.append(user_ex.userprofile_set.all()[0])
                            checkedin_shalist.append(user_ex.userprofile_set.all()[0].shaastra_id)
                        else:
                            pass
                    except:
                        if user_ex.userprofile_set.all()[0].gender == 'F':
                            userlist.append(user_ex.userprofile_set.all()[0])
                            shalist.append(user_ex.userprofile_set.all()[0].shaastra_id)
                
                tcheckinformset = modelformset_factory(IndividualCheckIn,form=IndividualForm,extra=len(userlist))
                formset = tcheckinformset(queryset=IndividualCheckIn.objects.filter(shaastra_ID__in=checkedin_shalist),initial=[{'shaastra_ID':sid,'check_in_control_room':'Sharavati','check_out_control_room':'Sharavati'} for sid in shalist])
                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/TeamDisplay.html',locals(),RequestContext(request))
                dajax.assign('#tab7',"innerHTML",html_content)
                return dajax.json()
        else:
            print form.errors
            show_alert(dajax,"error","Form is invalid")
            return dajax.json()
    else:
        form = TeamCheckinForm()
        html_content = render_to_string('hospi/TeamCheckin.html',locals(),RequestContext(request))
        dajax.assign("#tab7","innerHTML",html_content)
        return dajax.json()