Ejemplo n.º 1
0
def edit_subtask(request, subtask_id, owner_name=None):
    """
    Display full details of a SubTask.

    Note :
    Only owners of a subtask can (fully) edit the subtask (and that too only
    in their own page, ie. not while visiting some other user's page)

    Coords who have been assigned the SubTask can change only the Status.

    TODO :
    Validation
    Have an Edit Subtask view (like for Tasks)?
    """
    page_owner = get_page_owner(request, owner_name)

    user = request.user
    curr_subtask = SubTask.objects.get(id=subtask_id)
    curr_subtask_form = SubTaskForm(instance=curr_subtask)

    if curr_subtask.is_owner(user):
        is_owner = True
    else:
        # User is a Coord
        is_owner = False

    has_updated = False
    other_errors = False
    if request.method == 'POST':
        if is_owner:
            # Let the Core save the SubTask
            curr_subtask_form = SubTaskForm(request.POST,
                                            instance=curr_subtask)
            if curr_subtask_form.is_valid():
                curr_subtask_form.save()
                has_updated = True
            else:
                other_errors = True
        elif 'status' in request.POST:
            # Coord - allowed to change only the status
            curr_subtask.status = request.POST.get('status', 'O')
            curr_subtask.save()
            has_updated = True
            # Reinstantiate the form
            curr_subtask_form = SubTaskForm(instance=curr_subtask)
            print 'SubTask updated'
    comments, comment_form, comment_status = handle_comment(
        request=request,
        is_task_comment=False,
        object_id=subtask_id,
        other_errors=other_errors)
    if has_updated:
        # Redirect to the same page, at Vivek's request
        return redirect('tasks.views.edit_subtask',
                        owner_name=owner_name,
                        subtask_id=subtask_id)
    else:
        return render_to_response('tasks/edit_subtask.html',
                                  locals(),
                                  context_instance=global_context(request))
Ejemplo n.º 2
0
def financeedit(request, owner_name, request_id):
    page_owner = get_page_owner(request, owner_name)
    user = request.user
    curr_Request = Finance.objects.get(id=request_id)
    curr_subtask_form = SubTaskForm(request.POST, instance=curr_subtask)
    curr_subtask_form.save()
    return render_to_response('finance/edit_finance.html', locals())
Ejemplo n.º 3
0
def display_department_portal(request, owner_name=None, department_name=None):
    """
    Display all basic info about user's Department.
    """
    print 'Department name :', department_name
    # #added by vivek
    print "departmental portal here"
    shout_form = shout_box_form()
    shouts = shout_box.objects.all()
    print "done"

    page_owner = get_page_owner(request, owner_name)

    if department_name is None:
        department = page_owner.get_profile().get_dept()
    else:
        department = Group.objects.get(label__name='Department',
                                       name=department_name)
    display_dict = dict()
    display_dict['shouts'] = shouts  #by vivek
    display_dict['shout_form'] = shout_form  #by vivek
    display_dict['all_Tasks'] = get_timeline(page_owner)
    display_dict['updates'] = get_all_updates(department)
    display_dict['dept_cores_list'] = User.objects.filter(groups__name='Cores',
                                                          group=department)
    display_dict['dept_coords_list'] = User.objects.filter(
        groups__name='Coords', group=department)
    # display_dict['request'] = request
    return render_to_response('tasks/department_portal.html',
                              display_dict,
                              context_instance=global_context(request))
Ejemplo n.º 4
0
def financeedit(request,owner_name,request_id):
    page_owner = get_page_owner (request, owner_name)
    user = request.user
    curr_Request = Finance.objects.get(id = request_id)
    curr_subtask_form = SubTaskForm (request.POST, instance = curr_subtask)
    curr_subtask_form.save ()    
    return render_to_response('finance/edit_finance.html',locals())
Ejemplo n.º 5
0
def display_department_portal (request, owner_name = None, department_name = None):
    """
    Display all basic info about user's Department.
    """
    print 'Department name :', department_name
    # #added by vivek
    print "departmental portal here"
    shout_form=shout_box_form()
    shouts=shout_box.objects.all()
    print "done"

    page_owner = get_page_owner (request, owner_name)

    if department_name is None:
        department = page_owner.get_profile ().get_dept ()
    else:
        department = Group.objects.get (label__name = 'Department',
                                        name = department_name)
    display_dict = dict ()
    display_dict['shouts']=shouts#by vivek
    display_dict['shout_form']=shout_form#by vivek
    display_dict['all_Tasks'] = get_timeline (page_owner)
    display_dict['updates'] = get_all_updates (department)
    display_dict ['dept_cores_list'] = User.objects.filter (
        groups__name = 'Cores',
        group = department)
    display_dict ['dept_coords_list'] = User.objects.filter (
        groups__name = 'Coords',
        group = department)
    # display_dict['request'] = request
    return render_to_response('tasks/department_portal.html',
                              display_dict,
                              context_instance = global_context (request))
Ejemplo n.º 6
0
def edit_subtask (request, subtask_id, owner_name = None):
    """
    Display full details of a SubTask.

    Note :
    Only owners of a subtask can (fully) edit the subtask (and that too only
    in their own page, ie. not while visiting some other user's page)

    Coords who have been assigned the SubTask can change only the Status.

    TODO :
    Validation
    Have an Edit Subtask view (like for Tasks)?
    """
    page_owner = get_page_owner (request, owner_name)

    user = request.user
    curr_subtask = SubTask.objects.get (id = subtask_id)
    curr_subtask_form = SubTaskForm (instance = curr_subtask)

    if curr_subtask.is_owner (user):
        is_owner = True
    else:
        # User is a Coord
        is_owner = False

    has_updated = False
    other_errors = False
    if request.method == 'POST':
        if is_owner:
            # Let the Core save the SubTask
            curr_subtask_form = SubTaskForm (request.POST, instance = curr_subtask)
            if curr_subtask_form.is_valid ():
                curr_subtask_form.save ()
                has_updated = True
            else:
                other_errors = True
        elif 'status' in request.POST:
            # Coord - allowed to change only the status
            curr_subtask.status = request.POST.get ('status', 'O') 
            curr_subtask.save ()
            has_updated = True
            # Reinstantiate the form
            curr_subtask_form = SubTaskForm (instance = curr_subtask)
            print 'SubTask updated'
    comments, comment_form, comment_status = handle_comment (
        request = request,
        is_task_comment = False,
        object_id = subtask_id,
        other_errors = other_errors)
    if has_updated:
        # Redirect to the same page, at Vivek's request
        return redirect ('tasks.views.edit_subtask',
                         owner_name = owner_name, subtask_id = subtask_id)
    else:
        return render_to_response('tasks/edit_subtask.html',
                              locals(),
                              context_instance = global_context (request))
Ejemplo n.º 7
0
def handle_task_documents (request, owner_name = None, task_id = None, other_errors = False, only_validity = False):
    """
    Display a Inline Formset of Documents. Save or delete as required.

    Status :
    Invalid - for invalid document form(s)
    Success - successful upload
    Valid - Blank or valid formset

    only_validity : If True, only check whether the formset is valid
    or not and return formset and status

    other_errors : supposed to make the file field hold its value if
    there is some error in Tasks / SubTasks. Not working.

    Return the formset, status.
    """
    page_owner = get_page_owner (request, owner_name)

    TaskDocumentFormSet = inlineformset_factory (Task,
                                                 TaskDocument,
                                                 form = TaskDocumentForm,
                                                 extra = 2,
                                                 can_delete = True) 
    if task_id is not None:
        curr_task = Task.objects.get (id = task_id)
    else:
        curr_task = None
    status = 'OK'

    if request.method == 'POST':
        tdfs = TaskDocumentFormSet (request.POST,
                                    request.FILES,
                                    instance = curr_task)
        if only_validity:
            if tdfs.is_valid ():
                return tdfs, 'Valid'
            return tdfs, 'Invalid'
        if not other_errors:
            if tdfs.is_valid ():
                # From Django 1.3, FileField files won't get deleted, only
                # the model object will. So, we do it ourselves.
                for form in tdfs.deleted_forms:
                    delete_this_file (os.path.join (settings.MEDIA_ROOT,
                                                    form.instance.document.name))
                documents = tdfs.save (commit = False)
                for document in documents:
                    print 'Document : ', document
                    document.uploader = page_owner
                    document.save ()
                status = 'Success'
            else:
                # In case the formset isn't valid
                status = 'Invalid'
    if not other_errors and status != 'Invalid':
        tdfs = TaskDocumentFormSet (instance = curr_task)
    return tdfs, status
Ejemplo n.º 8
0
def handle_documents(request, owner_name=None):
    """
    Display a Model Formset for Documents of all labels.

    Allow Save or Delete.

    BUG : Description disappears after a transaction.
    """

    page_owner = get_page_owner(request, owner_name)

    DocumentFormSet = modelformset_factory(
        Document,
        form=DocumentForm,
        extra=1,
        can_delete=True,
    )

    dfs_list = []

    if request.method == 'POST':
        is_form_valid = True
        for label in doc_label_list:
            dfs_list.append(
                DocumentFormSet(
                    request.POST,
                    request.FILES,
                    prefix=label,
                    queryset=Document.objects.filter(label__name=label)))
            is_form_valid = is_form_valid and dfs_list[-1].is_valid()

        if is_form_valid:
            for dfs in dfs_list:
                # From Django 1.3, FileField files won't get deleted, only
                # the model object will. So, we do it ourselves.
                for form in dfs.deleted_forms:
                    delete_this_file(
                        os.path.join(settings.MEDIA_ROOT,
                                     form.instance.document.name))
                documents = dfs.save(commit=False)
                for document in documents:
                    print 'Document : ', document
                    document.uploader = page_owner
                    document.label = Label.objects.get(name=dfs.prefix)
                    document.save()
            return redirect('tasks.views.handle_documents', owner_name)

    dfs_list = []
    for label in doc_label_list:
        dfs_list.append(
            DocumentFormSet(
                prefix=label,
                queryset=Document.objects.filter(label__name=label)))
    dfs_heading_list = zip(dfs_list, doc_heading_list)
    return render_to_response('tasks/documents.html',
                              locals(),
                              context_instance=global_context(request))
Ejemplo n.º 9
0
def display_portal (request, owner_name = None):
    """
    Display owner's portal.
    """
    page_owner = get_page_owner (request, owner_name)
    request.session['page_owner']=page_owner;
    print page_owner , "/n/n/n/n"
    if is_core (page_owner):
        return display_core_portal (request, page_owner)
    else:
        return display_coord_portal (request, page_owner)
Ejemplo n.º 10
0
def display_portal(request, owner_name=None):
    """
    Display owner's portal.
    """
    page_owner = get_page_owner(request, owner_name)
    request.session['page_owner'] = page_owner
    print page_owner, "/n/n/n/n"
    if is_core(page_owner):
        return display_core_portal(request, page_owner)
    else:
        return display_coord_portal(request, page_owner)
Ejemplo n.º 11
0
def handle_documents (request, owner_name = None):
    """
    Display a Model Formset for Documents of all labels.

    Allow Save or Delete.

    BUG : Description disappears after a transaction.
    """

    page_owner = get_page_owner (request, owner_name)

    DocumentFormSet = modelformset_factory (
        Document,
        form = DocumentForm,
        extra = 1,
        can_delete = True,) 

    dfs_list = []

    if request.method == 'POST':
        is_form_valid = True
        for label in doc_label_list:
            dfs_list.append (DocumentFormSet (request.POST,
                                              request.FILES,
                                              prefix   = label,
                                              queryset = Document.objects.filter (
                                                  label__name = label)))
            is_form_valid = is_form_valid and dfs_list[-1].is_valid ()

        if is_form_valid:
            for dfs in dfs_list:
                # From Django 1.3, FileField files won't get deleted, only
                # the model object will. So, we do it ourselves.
                for form in dfs.deleted_forms:
                    delete_this_file (os.path.join (settings.MEDIA_ROOT,
                                                    form.instance.document.name))
                documents = dfs.save (commit = False)
                for document in documents:
                    print 'Document : ', document
                    document.uploader = page_owner
                    document.label = Label.objects.get (name = dfs.prefix)
                    document.save ()
            return redirect ('tasks.views.handle_documents', owner_name)

    dfs_list = []
    for label in doc_label_list:
        dfs_list.append (DocumentFormSet (prefix = label,
                                          queryset = Document.objects.filter (
                                              label__name = label)))
    dfs_heading_list = zip (dfs_list, doc_heading_list)
    return render_to_response('tasks/documents.html',
                              locals(),
                              context_instance = global_context (request))
Ejemplo n.º 12
0
def edit_task_subtasks(request, task_id, owner_name=None):
    """Edit subtasks and their documents for a given task."""

    task = get_object_or_404(Task, id=task_id)
    page_owner = get_page_owner(request, owner_name)
    print task

    if request.method == 'POST':
        try:
            formset = NestedSubTaskFormset(request.POST,
                                           request.FILES,
                                           instance=task)
        except ValidationError:
            formset = None
        if formset and formset.is_valid():
            formset.save_all(user=page_owner)
            return redirect('tasks.views.edit_task_subtasks',
                            task_id=task.id,
                            owner_name=request.user.username)

    # if request.method == 'POST':
    #     formset = SubTaskFormset (request.POST, instance=task)

    #     if formset.is_valid ():
    #         subtasks = formset.save_all ()
    #         return redirect ('task_view', task_id=task.id)
    else:
        formset = NestedSubTaskFormset(instance=task)

    # For getting Template Form
    subtaskfs = DummySubTaskFormSet(instance=task)
    template_form = str(subtaskfs.empty_form)
    print 'Template Form : ', template_form
    doc_template_form = str(formset.my_empty_form())
    doc_template_form = re.sub('__prefix__', '__doc-prefix__',
                               doc_template_form)
    doc_template_form = re.sub('1(?!0)', '__prefix__', doc_template_form)
    comment_template_form = str(
        SubTaskCommentForm(prefix='SUBTASKCOMMENT___prefix__'))
    template_form += (doc_template_form + comment_template_form)

    print 'Doc Template Form : ', doc_template_form

    return render_to_response('tasks/edit_subtasks.html', {
        'task': task,
        'subtasks': formset,
        'template_form': template_form,
    },
                              context_instance=global_context(request))
Ejemplo n.º 13
0
def display_task(request, task_id, owner_name=None):
    """
    Display full details of a Task.
    TODO :
    Validation
    Back Button to go back
    """
    page_owner = get_page_owner(request, owner_name)
    print 'Display Task - Task ID : ', task_id
    curr_task = Task.objects.get(id=task_id)
    is_owner = curr_task.is_owner(request.user)
    comments = TaskComment.objects.filter(task__id=task_id)
    return render_to_response('tasks/display_task.html',
                              locals(),
                              context_instance=global_context(request))
Ejemplo n.º 14
0
def display_task (request, task_id, owner_name = None):
    """
    Display full details of a Task.
    TODO :
    Validation
    Back Button to go back
    """
    page_owner = get_page_owner (request, owner_name)
    print 'Display Task - Task ID : ', task_id
    curr_task = Task.objects.get (id = task_id)
    is_owner = curr_task.is_owner (request.user)
    comments = TaskComment.objects.filter (task__id = task_id)
    return render_to_response('tasks/display_task.html',
                              locals(),
                              context_instance = global_context (request))
Ejemplo n.º 15
0
def display_subtask(request, subtask_id, owner_name=None):
    """
    Display full details of a SubTask.
    TODO :
    Validation
    Have an Edit Subtask view (like for Tasks)?
    """
    page_owner = get_page_owner(request, owner_name)
    user = request.user
    curr_subtask = SubTask.objects.get(id=subtask_id)
    is_owner = curr_subtask.is_owner(user)
    comments = SubTaskComment.objects.filter(subtask__id=subtask_id)

    return render_to_response('tasks/display_subtask.html',
                              locals(),
                              context_instance=global_context(request))
Ejemplo n.º 16
0
def display_subtask (request, subtask_id, owner_name = None):
    """
    Display full details of a SubTask.
    TODO :
    Validation
    Have an Edit Subtask view (like for Tasks)?
    """
    page_owner = get_page_owner (request, owner_name)
    user = request.user
    curr_subtask = SubTask.objects.get (id = subtask_id)
    is_owner = curr_subtask.is_owner (user)
    comments = SubTaskComment.objects.filter (subtask__id = subtask_id)

    return render_to_response('tasks/display_subtask.html',
                              locals(),
                              context_instance = global_context (request))
Ejemplo n.º 17
0
def edit_task_subtasks (request, task_id, owner_name = None):
    """Edit subtasks and their documents for a given task."""

    task = get_object_or_404 (Task, id = task_id)
    page_owner = get_page_owner (request, owner_name)
    print task

    if request.method == 'POST':
        try:
            formset = NestedSubTaskFormset (request.POST, request.FILES, instance = task)
        except ValidationError:
            formset = None
        if formset and formset.is_valid():
            formset.save_all (user = page_owner)
            return redirect ('tasks.views.edit_task_subtasks', task_id=task.id, owner_name = request.user.username)

    # if request.method == 'POST':
    #     formset = SubTaskFormset (request.POST, instance=task)

    #     if formset.is_valid ():
    #         subtasks = formset.save_all ()
    #         return redirect ('task_view', task_id=task.id)
    else:
        formset = NestedSubTaskFormset (instance=task)

    # For getting Template Form
    subtaskfs = DummySubTaskFormSet (instance = task)
    template_form = str (subtaskfs.empty_form)
    print 'Template Form : ', template_form
    doc_template_form = str (formset.my_empty_form ())
    doc_template_form = re.sub ('__prefix__', '__doc-prefix__', doc_template_form)
    doc_template_form = re.sub ('1(?!0)', '__prefix__', doc_template_form)
    comment_template_form = str (SubTaskCommentForm (prefix = 'SUBTASKCOMMENT___prefix__'))
    template_form += (doc_template_form + comment_template_form)

    print 'Doc Template Form : ', doc_template_form

    return render_to_response ('tasks/edit_subtasks.html',
                               {'task':task,
                                'subtasks':formset,
                                'template_form':template_form,
                               },
                               context_instance = global_context (request))
Ejemplo n.º 18
0
def handle_updates(request, owner_name=None):
    """
    Used by coords to send updates to Core.
    Cores will just see the updates they have received.

    Return a dict containing update variables.
    """
    page_owner = get_page_owner(request, owner_name)

    update_dict = dict()
    if page_owner.groups.filter(name='Coords'):
        # For Coords
        update_form = UpdateForm()
        update_status = "Blank"
        update_dict['updates'] = Update.objects.filter(author=page_owner)
        update_dict['update_form'] = update_form
        update_dict['update_status'] = update_status
    else:
        # For Core, just display all updates for his dept
        update_dict['updates'] = get_all_updates(
            page_owner.get_profile().get_dept())

    if request.method == 'POST':
        update_form = UpdateForm(request.POST)
        if update_form.is_valid():
            new_update = update_form.save(commit=False)
            new_update.author = page_owner
            new_update.save()
            update_form = UpdateForm()
            update_status = "Success"
            update_dict['update_status'] = update_status
            return update_dict
        else:
            update_status = "Failed"
            update_dict['update_status'] = update_status
            update_dict['update_form'] = update_form
            return update_dict
    return update_dict
Ejemplo n.º 19
0
def handle_updates (request, owner_name = None):
    """
    Used by coords to send updates to Core.
    Cores will just see the updates they have received.

    Return a dict containing update variables.
    """
    page_owner = get_page_owner (request, owner_name)

    update_dict = dict ()
    if page_owner.groups.filter (name = 'Coords'):
        # For Coords
        update_form = UpdateForm ()
        update_status = "Blank"
        update_dict['updates'] = Update.objects.filter (author = page_owner)
        update_dict['update_form'] = update_form
        update_dict['update_status'] = update_status
    else:
        # For Core, just display all updates for his dept
        update_dict['updates'] = get_all_updates (
            page_owner.get_profile ().get_dept ())

    if request.method == 'POST':
        update_form = UpdateForm (request.POST)            
        if update_form.is_valid():
            new_update = update_form.save (commit = False)
            new_update.author = page_owner
            new_update.save ()
            update_form = UpdateForm ()
            update_status = "Success"
            update_dict['update_status'] = update_status
            return update_dict
        else:
            update_status = "Failed"
            update_dict['update_status'] = update_status
            update_dict['update_form'] = update_form
            return update_dict
    return update_dict
Ejemplo n.º 20
0
def handle_task_documents(request,
                          owner_name=None,
                          task_id=None,
                          other_errors=False,
                          only_validity=False):
    """
    Display a Inline Formset of Documents. Save or delete as required.

    Status :
    Invalid - for invalid document form(s)
    Success - successful upload
    Valid - Blank or valid formset

    only_validity : If True, only check whether the formset is valid
    or not and return formset and status

    other_errors : supposed to make the file field hold its value if
    there is some error in Tasks / SubTasks. Not working.

    Return the formset, status.
    """
    page_owner = get_page_owner(request, owner_name)

    TaskDocumentFormSet = inlineformset_factory(Task,
                                                TaskDocument,
                                                form=TaskDocumentForm,
                                                extra=2,
                                                can_delete=True)
    if task_id is not None:
        curr_task = Task.objects.get(id=task_id)
    else:
        curr_task = None
    status = 'OK'

    if request.method == 'POST':
        tdfs = TaskDocumentFormSet(request.POST,
                                   request.FILES,
                                   instance=curr_task)
        if only_validity:
            if tdfs.is_valid():
                return tdfs, 'Valid'
            return tdfs, 'Invalid'
        if not other_errors:
            if tdfs.is_valid():
                # From Django 1.3, FileField files won't get deleted, only
                # the model object will. So, we do it ourselves.
                for form in tdfs.deleted_forms:
                    delete_this_file(
                        os.path.join(settings.MEDIA_ROOT,
                                     form.instance.document.name))
                documents = tdfs.save(commit=False)
                for document in documents:
                    print 'Document : ', document
                    document.uploader = page_owner
                    document.save()
                status = 'Success'
            else:
                # In case the formset isn't valid
                status = 'Invalid'
    if not other_errors and status != 'Invalid':
        tdfs = TaskDocumentFormSet(instance=curr_task)
    return tdfs, status
Ejemplo n.º 21
0
def edit_task (request, task_id = None, owner_name = None):
    """
    Edit existing Task.

    TODO :
    Do user validation (should have permission)
    Allow delete Task facility (?)
    Cancel Edit
    Save Draft
    """

    page_owner = get_page_owner (request, owner_name)
    user = request.user

    if task_id:
        # Existing Task
        curr_task = Task.objects.get (id = task_id)
        is_new_task = False
    else:
        # New Task
        curr_task = Task (creator = user)
        is_new_task = True

    other_errors = False
    task_doc_status = 'OK'

    # Simple test for autocomplete feature
    subject_data = []
    for task in Task.objects.all ():
        subject_data.append (task.subject)
    # print 'Subject data : ', subject_data
    subject_data_js = simplejson.dumps (subject_data)


    SubTaskFormSet = inlineformset_factory (Task,
                                            SubTask,
                                            form = SubTaskForm,
                                            exclude = subtask_exclusion_tuple,
                                            extra = 0,
                                            can_delete = True)
    # TagFormSet = modelformset_factory (Tag, extra = 1, can_delete = True,
    #                                    exclude = ('task',))
    # subtask_comments = []
    if request.method == 'POST':
        # Get the submitted formset

        subtaskfs = SubTaskFormSet (request.POST,
                                    instance = curr_task)
        template_form = subtaskfs.empty_form

        task_form = TaskForm (request.POST, instance = curr_task)
        if task_form.is_valid () and subtaskfs.is_valid ():
            # if not is_new_task:
            #     tdfs, task_doc_status = handle_task_documents (
            #         request, owner_name, task_id, other_errors, only_validity = True)
            # if task_doc_status != 'Invalid':
            curr_task = task_form.save (commit = False)
            curr_task.save()
            print 'Task : ', curr_task

            comments, comment_form, comment_status = handle_comment (
                request = request, is_task_comment = True, object_id = task_id)

            # tagfs = TagFormSet (request.POST)
            # if tagfs.is_valid ():
            #     tags = tagfs.save (commit = False)
            #     for tag in tags:
            #         tag.save ()
            #         tag.task.add (curr_task)
            #     tagfs.save_m2m () # Necessary, since we used commit = False

            # st_comment_list = [handle_comment (request, False, form.instance.id) for form in subtaskfs]
            # if not is_new_task:
            tdfs, task_doc_status = handle_task_documents (
                request, owner_name, curr_task.id, other_errors = other_errors)

            # Only the filled forms will be stored in subtasks
            # Also, subtasks marked for deletion are deleted here.
            subtasks = subtaskfs.save (commit = False)
            for subtask in subtasks:
                print 'Subtask : ', subtask
                subtask.creator = user
                subtask.status = DEFAULT_STATUS
                # In case it's a new form (inline formset won't
                # fill in the task in that case)
                subtask.task = curr_task
                subtask.save ()
            subtaskfs.save_m2m () # Necessary, since we used commit = False

            return redirect ('tasks.views.display_portal',
                             owner_name = owner_name)
        else:
            # One or more Forms are invalid
            other_errors = True
    else:
        task_form = TaskForm (instance = curr_task)

        subtaskfs = SubTaskFormSet (instance = curr_task)
        template_form = subtaskfs.empty_form
    print 'Template Form : ', template_form
    # if not is_new_task and task_doc_status != 'Invalid':
    tdfs, task_doc_status = handle_task_documents (request,
                                                   owner_name,
                                                   task_id,
                                                   other_errors)
    # tagfs = TagFormSet (queryset = Tag.objects.filter (task__id = task_id))
    comments, comment_form, comment_status = handle_comment (
        request = request,
        is_task_comment = True,
        object_id = task_id,
        other_errors = other_errors
        )
    return render_to_response('tasks/edit_task.html',
                              locals(),
                              context_instance = global_context (request))
Ejemplo n.º 22
0
def edit_task(request, task_id=None, owner_name=None):
    """
    Edit existing Task.

    TODO :
    Do user validation (should have permission)
    Allow delete Task facility (?)
    Cancel Edit
    Save Draft
    """

    page_owner = get_page_owner(request, owner_name)
    user = request.user

    if task_id:
        # Existing Task
        curr_task = Task.objects.get(id=task_id)
        is_new_task = False
    else:
        # New Task
        curr_task = Task(creator=user)
        is_new_task = True

    other_errors = False
    task_doc_status = 'OK'

    # Simple test for autocomplete feature
    subject_data = []
    for task in Task.objects.all():
        subject_data.append(task.subject)
    # print 'Subject data : ', subject_data
    subject_data_js = simplejson.dumps(subject_data)

    SubTaskFormSet = inlineformset_factory(Task,
                                           SubTask,
                                           form=SubTaskForm,
                                           exclude=subtask_exclusion_tuple,
                                           extra=0,
                                           can_delete=True)
    # TagFormSet = modelformset_factory (Tag, extra = 1, can_delete = True,
    #                                    exclude = ('task',))
    # subtask_comments = []
    if request.method == 'POST':
        # Get the submitted formset

        subtaskfs = SubTaskFormSet(request.POST, instance=curr_task)
        template_form = subtaskfs.empty_form

        task_form = TaskForm(request.POST, instance=curr_task)
        if task_form.is_valid() and subtaskfs.is_valid():
            # if not is_new_task:
            #     tdfs, task_doc_status = handle_task_documents (
            #         request, owner_name, task_id, other_errors, only_validity = True)
            # if task_doc_status != 'Invalid':
            curr_task = task_form.save(commit=False)
            curr_task.save()
            print 'Task : ', curr_task

            comments, comment_form, comment_status = handle_comment(
                request=request, is_task_comment=True, object_id=task_id)

            # tagfs = TagFormSet (request.POST)
            # if tagfs.is_valid ():
            #     tags = tagfs.save (commit = False)
            #     for tag in tags:
            #         tag.save ()
            #         tag.task.add (curr_task)
            #     tagfs.save_m2m () # Necessary, since we used commit = False

            # st_comment_list = [handle_comment (request, False, form.instance.id) for form in subtaskfs]
            # if not is_new_task:
            tdfs, task_doc_status = handle_task_documents(
                request, owner_name, curr_task.id, other_errors=other_errors)

            # Only the filled forms will be stored in subtasks
            # Also, subtasks marked for deletion are deleted here.
            subtasks = subtaskfs.save(commit=False)
            for subtask in subtasks:
                print 'Subtask : ', subtask
                subtask.creator = user
                subtask.status = DEFAULT_STATUS
                # In case it's a new form (inline formset won't
                # fill in the task in that case)
                subtask.task = curr_task
                subtask.save()
            subtaskfs.save_m2m()  # Necessary, since we used commit = False

            return redirect('tasks.views.display_portal',
                            owner_name=owner_name)
        else:
            # One or more Forms are invalid
            other_errors = True
    else:
        task_form = TaskForm(instance=curr_task)

        subtaskfs = SubTaskFormSet(instance=curr_task)
        template_form = subtaskfs.empty_form
    print 'Template Form : ', template_form
    # if not is_new_task and task_doc_status != 'Invalid':
    tdfs, task_doc_status = handle_task_documents(request, owner_name, task_id,
                                                  other_errors)
    # tagfs = TagFormSet (queryset = Tag.objects.filter (task__id = task_id))
    comments, comment_form, comment_status = handle_comment(
        request=request,
        is_task_comment=True,
        object_id=task_id,
        other_errors=other_errors)
    return render_to_response('tasks/edit_task.html',
                              locals(),
                              context_instance=global_context(request))
Ejemplo n.º 23
0
def finance(request,
            request_id=-1,
            department_str=None,
            portal=None,
            owner_name=None,
            edit=False):
    """
    Function called when finance portal is opened. Redirects to eventcoord if event coord logs in.
    Finance coords can edit any budget of any event. They can approve requests by events.
    """
    print portal
    success = False
    print request_id
    page_owner = get_page_owner(request, owner_name)
    user = request.user
    if (str(user) == str(page_owner)):
        allow_adding_request = True
    print user.get_profile().get_dept()
    # Check if event coord
    if str(user.get_profile().get_dept()) == "Events":
        return HttpResponseRedirect("events/")
    if department_str == None or department_str == "":
        return HttpResponseRedirect(str(user.get_profile().get_dept()))

    if str(user.get_profile().get_dept()) == "Finance":
        finance_coord = True
        #        all_events_data = get_all_departments()
        Form = BudgetFormCoord
        all_events_data = get_all_events()
        all_department_data = get_all_departments()

    else:
        Form = BudgetForm
        finance_coord = False
    if finance_coord or str(user) == str(page_owner):
        editable = True
        allow_adding_request = True
    finance_form = Form()
    if department_str:
        department_object = Group.objects.filter(label__name='Department',
                                                 name=department_str)
    if not department_str:
        department_object = Group.objects.filter(
            label__name='Department', name=user.get_profile().get_dept())
    user_department = department_object[0].name
    advance_portal_finance_data = get_all_eventsadvanceportal()
    self_requests = Budget_Department.objects.filter(
        department=department_object)
    sum_amount_a, sum_amount_b, sum_amount_r = calculate_sums(self_requests)
    if request_id >= 0:
        request_to_edit = Budget_Department.objects.get(id=request_id)
        Edit = True
        finance_form = Form(
            initial={
                'particular': request_to_edit.particular,
                'requirement_date': request_to_edit.requirement_date,
                'amount_a': request_to_edit.amount_a,
                'amount_b': request_to_edit.amount_b,
                'amount_revised': request_to_edit.amount_revised,
                'status': request_to_edit.status
            })
        if request.method == 'POST':
            finance_form = Form(request.POST)
            if finance_form.is_valid():
                request_to_edit.particular = finance_form.cleaned_data[
                    'particular']
                request_to_edit.requirement_date = finance_form.cleaned_data[
                    'requirement_date']
                request_to_edit.amount_a = finance_form.cleaned_data[
                    'amount_a']
                request_to_edit.amount_b = finance_form.cleaned_data[
                    'amount_b']
                if finance_coord:
                    request_to_edit.amount_revised = finance_form.cleaned_data[
                        'amount_revised']
                    request_to_edit.status = finance_form.cleaned_data[
                        'status']
                success = True
                request_to_edit.save()
                #                return render_to_response('finance/budget_portal.html',locals(), context_instance = global_context (request))
                return HttpResponseRedirect("../")
        return render_to_response('finance/budget_portal.html',
                                  locals(),
                                  context_instance=global_context(request))


#            return redirect ('finance.views.finance', locals())

    if request.method == 'POST':
        finance_form = Form(request.POST)
        if finance_form.is_valid():
            new_request = finance_form.save(commit=False)
            success = True
            new_request.requester = user
            if not new_request.amount_revised:
                new_request.amount_revised = 0
            new_request.department = Group.objects.filter(
                label__name='Department', name=department_str)[0]
            new_request.save()
            return render_to_response('finance/budget_portal.html',
                                      locals(),
                                      context_instance=global_context(request))
    return render_to_response('finance/budget_portal.html',
                              locals(),
                              context_instance=global_context(request))
Ejemplo n.º 24
0
def finance(request,request_id=-1,department_str=None,portal=None,owner_name=None,edit=False):
    """
    Function called when finance portal is opened. Redirects to eventcoord if event coord logs in.
    Finance coords can edit any budget of any event. They can approve requests by events.
    """
    print portal
    success = False
    print request_id
    page_owner = get_page_owner (request, owner_name)
    user = request.user
    if (str(user) == str(page_owner)):
        allow_adding_request = True
    print user.get_profile().get_dept ()
    # Check if event coord
    if str(user.get_profile().get_dept ()) == "Events":
        return HttpResponseRedirect("events/")
    if department_str == None or department_str == "":
        return HttpResponseRedirect(str(user.get_profile().get_dept ()))
        
    if str(user.get_profile().get_dept ()) == "Finance":
        finance_coord = True
#        all_events_data = get_all_departments()
        Form = BudgetFormCoord
        all_events_data = get_all_events()
        all_department_data = get_all_departments()        

    else:
        Form = BudgetForm      
        finance_coord = False
    if finance_coord or str(user) == str(page_owner):
        editable = True
        allow_adding_request = True        
    finance_form = Form()
    if department_str:
        department_object = Group.objects.filter(label__name = 'Department',
                                                 name = department_str)
    if not department_str:
        department_object = Group.objects.filter(label__name = 'Department',
                                                 name = user.get_profile().get_dept ())
    user_department = department_object[0].name
    advance_portal_finance_data = get_all_eventsadvanceportal()
    self_requests = Budget_Department.objects.filter(department = department_object)
    sum_amount_a,sum_amount_b,sum_amount_r = calculate_sums(self_requests)    
    if request_id >= 0:
        request_to_edit = Budget_Department.objects.get (id = request_id)
        Edit = True
        finance_form = Form(initial={'particular':request_to_edit.particular, 'requirement_date':request_to_edit.requirement_date, 'amount_a':request_to_edit.amount_a, 'amount_b':request_to_edit.amount_b, 'amount_revised':request_to_edit.amount_revised, 'status':request_to_edit.status})
        if request.method == 'POST':        
            finance_form = Form(request.POST)
            if finance_form.is_valid():
                request_to_edit.particular = finance_form.cleaned_data['particular']
                request_to_edit.requirement_date = finance_form.cleaned_data['requirement_date']
                request_to_edit.amount_a = finance_form.cleaned_data['amount_a']
                request_to_edit.amount_b = finance_form.cleaned_data['amount_b']
                if finance_coord:
                    request_to_edit.amount_revised = finance_form.cleaned_data['amount_revised']
                    request_to_edit.status = finance_form.cleaned_data['status']                                                                                
                success = True
                request_to_edit.save()
#                return render_to_response('finance/budget_portal.html',locals(), context_instance = global_context (request))
                return HttpResponseRedirect("../")
        return render_to_response('finance/budget_portal.html',locals(), context_instance = global_context (request))
#            return redirect ('finance.views.finance', locals())

    if request.method == 'POST':
        finance_form = Form(request.POST)
        if finance_form.is_valid():
            new_request = finance_form.save (commit = False)
            success = True
            new_request.requester = user
            if not new_request.amount_revised:
                new_request.amount_revised = 0                        
            new_request.department = Group.objects.filter(
                label__name = 'Department',
                name = department_str)[0]
            new_request.save()
            return render_to_response('finance/budget_portal.html',locals(), context_instance = global_context (request))
    return render_to_response('finance/budget_portal.html',locals(),context_instance = global_context (request)) 
Ejemplo n.º 25
0
def eventcoord(request, event="", request_id=-1, owner_name=None, Edit=False):
    """
    Function called when an event coord logs in. Displays his requests.
    Allows him to add new requests for his event.
    Each event has a separate page
    """

    event_name = event
    event_coord = True
    user = request.user
    coordinating = Group.objects.filter(label__name='Events', members=user)
    page_owner = get_page_owner(request, owner_name)

    for item in coordinating:
        if event in str(item.name):
            allow_adding_request = True
    Form = BudgetFormEvent
    if str(user.get_profile().get_dept()) == "Finance":
        finance_coord = True
        allow_adding_request = True
        all_events_data = get_all_events()
        all_department_data = get_all_departments()
        Form = BudgetFormCoordEvent
    else:
        finance_coord = False
    if (str(user) != str(page_owner)):
        allow_adding_request = False
    if event == "":
        event_list = []
        for item in coordinating:

            event_list.append(item.name)
        return render_to_response('finance/select_event.html',
                                  locals(),
                                  context_instance=global_context(request))
    finance_form = Form()
    advance_portal_finance_data = get_all_eventsadvanceportal()
    # Get requests created by an event
    self_requests = Budget_Event.objects.filter(
        event=Group.objects.filter(label__name='Events', name=event))
    accepted_requests_A = Budget_Event.objects.filter(
        event=Group.objects.filter(label__name='Events', name=event),
        status='A')
    required_items = Budget_Event.objects.filter(
        event=Group.objects.get(label__name='Event', name=event))
    advance_payment_objs = []
    for item in accepted_requests_A:
        advance_payment_objs += Advance_Payment.objects.filter(
            link=item, finance_approval=True)

    total_budget, balance_budget_total = calculate_budget(
        accepted_requests_A, advance_payment_objs)

    accepted_requests_A_list = accepted_requests_A.values_list(
        'id', 'amount_revised')
    string_r_A = {}
    status_A = {}
    form_tuple = []
    ids_A = []
    try:
        buffer_exist = Buffer.objects.get(
            event=Group.objects.get(label__name='Event', name=event))
        if buffer_exist.finance_approval == True:
            buffer_approved = True
    except:
        pass
    for i in range(0, len(accepted_requests_A_list)):
        # Get data to be displayed on advance payment portal
        all_approved_requests = Advance_Payment.objects.filter(
            link=Budget_Event.objects.get(id=accepted_requests_A_list[i][0]),
            finance_approval=True)
        balance_budget = accepted_requests_A_list[i][1] - sum([
            x[0] for x in all_approved_requests.values_list('amount_request')
        ])
        not_approved_objs = Advance_Payment.objects.filter(
            link=Budget_Event.objects.get(id=accepted_requests_A_list[i][0]),
            finance_approval=False)
        all_objs_for_item = Advance_Payment.objects.filter(
            link=Budget_Event.objects.get(id=accepted_requests_A_list[i][0]))
        not_approved_amt = sum(
            [x[0] for x in not_approved_objs.values_list('amount_request')])
        temp = []
        ids_A.append(accepted_requests_A_list[i][0])
        #        money[accepted_requests_A_list[i][0]] = AdvancePortalForm(prefix=str(accepted_requests_A_list[i][0]))
        money = AdvancePortalForm(prefix=str(accepted_requests_A_list[i][0]))

        boolformfin = BoolForm(prefix=str(accepted_requests_A_list[i][0]) +
                               "fin")
        boolformeven = BoolForm(prefix=str(accepted_requests_A_list[i][0]) +
                                "even")
        temp.append(accepted_requests_A[i])
        temp.append(money)

        try:
            filteritem = Budget_Event.objects.get(
                id=accepted_requests_A_list[i][0])
            exist = Advance_Payment.objects.get(link=filteritem)
            Advance_object = exist
        except:
            exist = Advance_Payment(amount_request=0, link=filteritem)
        try:
            if exist:
                status_A = accepted_requests_A_list[i][1] - exist.amount_request
            else:
                status_A = accepted_requests_A_list[i][1]
        except:
            pass
        temp.append(status_A)
        try:
            temp.append(exist.amount_request)
        except:
            temp.append(0)
        if (is_core(user) and finance_coord):
            d = {}
            user_is_core = True
            try:
                if (exist.finance_approval == False):
                    temp.append(boolformfin)
                else:
                    d['bool_val'] = "Approved"
                    temp.append(d)
                    d = {}

                if (exist.events_approval == False):
                    d['bool_val'] = "Not yet Approved"
                    temp.append(d)
                    d = {}

                else:
                    d['bool_val'] = "Approved"
                    temp.append(d)
                    d = {}
            except:
                temp.append(boolformfin)
                d['bool_val'] = "Not yet Approved"
                temp.append(d)
                d = {}

        elif (is_core(user)):
            d = {}
            user_is_core = True
            try:
                if (exist.finance_approval == False):
                    d['bool_val'] = "Not yet Approved"
                    temp.append(d)
                    d = {}
                else:
                    d['bool_val'] = "Approved"
                    temp.append(d)
                    d = {}
                if (exist.events_approval == False):
                    temp.append(boolformeven)
                else:
                    d['bool_val'] = "Approved"
                    temp.append(d)
                    d = {}
            except:
                temp.append("Not yet Approved")
                temp.append(boolformeven)
        else:
            d = {}
            if (exist.finance_approval == False):
                d['bool_val'] = "Not yet Approved"
                temp.append(d)
                d = {}
            else:
                d['bool_val'] = "Approved"
                temp.append(d)
                d = {}
            if (exist.events_approval == False):
                d['bool_val'] = "Not yet Approved"
                temp.append(d)
                d = {}
            else:
                d['bool_val'] = "Approved"
                temp.append(d)
                d = {}
        now = datetime.date.today()
        due = filteritem.requirement_date
        try:
            if Advance_object.finance_approval:
                temp.append("Accepted")
            else:
                temp.append("Available")
            Advance_object = []
        except:
            if (now > due):
                temp.append("Rejected")
            else:
                temp.append("Available")

        temp.append(not_approved_amt)

        temp3 = []
        for item in all_objs_for_item:
            temp2 = []
            temp2.append(item)
            if item.finance_approval == True:
                dicta = {}
                dicta['bool_val'] = "Approved"
                temp2.append(dicta)
            else:
                if (is_core(user)):
                    temp2.append(BoolForm(prefix=str(item.id)))
                else:
                    dicta = {}
                    dicta['bool_val'] = "Not Approved"
                    temp2.append(dicta)
            if (item.finance_approval == True):
                temp2.append("Accepted")
            elif (now > due):
                temp2.append("Rejected")
            else:
                temp2.append("Available")
            temp3.append(temp2)
        temp.append(temp3)
        temp.append(balance_budget)
        form_tuple.append(temp)

    temp = []
    # For Buffer in Advance payment Portal
    bufferform = []
    bufferform.append(BufferForm())
    # For Buffer
    temp = []
    buffer_A = []
    try:
        exist = Buffer.objects.get(
            event=Group.objects.get(label__name='Event', name=event))
    except:
        exist = Buffer(
            event=Group.objects.get(label__name='Event', name=event))
    buffer_A = []
    buffer_A.append(exist)
    # If core, then allow him to approve requests.
    if (is_core(user) and finance_coord):
        d = {}
        user_is_core = True
        try:
            if (exist.finance_approval == False):
                temp.append(BoolForm(prefix=str("bufferfin")))
            else:
                d['bool_val'] = "Approved"
                temp.append(d)
                d = {}
            if (exist.events_approval == False):
                d['bool_val'] = "Not yet Approved"
                temp.append(d)
                d = {}
            else:
                d['bool_val'] = "Approved"
                temp.append(d)
                d = {}
        except:
            temp.append(boolformfin)
            d['bool_val'] = "Not yet Approved"
            temp.append(d)
    elif (is_core(user)):
        d = {}
        user_is_core = True
        try:
            if (exist.finance_approval == False):
                d['bool_val'] = "Not yet Approved"
                temp.append(d)
                d = {}
            else:
                d['bool_val'] = "Approved"
                temp.append(d)
                d = {}
            if (exist.events_approval == False):
                temp.append(BoolForm(prefix=str("buffereven")))
            else:
                d['bool_val'] = "Approved"
                temp.append(d)
                d = {}
        except:
            temp.append("Not yet Approved")
            temp.append(BoolForm(prefix=str("buffereven")))
    else:
        d = {}
        if (exist.finance_approval == False):
            d['bool_val'] = "Not yet Approved"
            temp.append(d)
            d = {}
        else:
            d['bool_val'] = "Approved"
            temp.append(d)
            d = {}
        if (exist.events_approval == False):
            d['bool_val'] = "Not yet Approved"
            temp.append(d)
            d = {}
        else:
            d['bool_val'] = "Approved"
            temp.append(d)
            d = {}

# Amount Requested

    buffer_A.append(temp)
    sum_amount_a, sum_amount_b, sum_amount_r = calculate_sums(self_requests)

    if request_id >= 0:
        request_to_edit = Budget_Event.objects.get(id=request_id)
        Edit = True
        finance_form = Form(
            initial={
                'particular': request_to_edit.particular,
                'requirement_date': request_to_edit.requirement_date,
                'amount_a': request_to_edit.amount_a,
                'amount_b': request_to_edit.amount_b,
                'amount_revised': request_to_edit.amount_revised,
                'status': request_to_edit.status
            })
        if request.method == 'POST':
            finance_form = Form(request.POST)
            if finance_form.is_valid():
                request_to_edit.particular = finance_form.cleaned_data[
                    'particular']
                request_to_edit.requirement_date = finance_form.cleaned_data[
                    'requirement_date']
                request_to_edit.amount_a = finance_form.cleaned_data[
                    'amount_a']
                request_to_edit.amount_b = finance_form.cleaned_data[
                    'amount_b']
                success = True
                if finance_coord:
                    request_to_edit.amount_revised = finance_form.cleaned_data[
                        'amount_revised']
                    request_to_edit.status = finance_form.cleaned_data[
                        'status']
                request_to_edit.save()
                request_id = -1
                return HttpResponseRedirect("./")
        return render_to_response('finance/budget_portal.html',
                                  locals(),
                                  context_instance=global_context(request))


#    return redirect ('finance.views.finance', locals())
    print "nearing"
    if request.method == 'POST':
        finance_form = Form(request.POST)
        print "saving"
        if finance_form.is_valid():
            new_request = finance_form.save(commit=False)
            success = True
            new_request.requester = user
            if not new_request.amount_revised:
                new_request.amount_revised = 0
            new_request.event = Group.objects.filter(label__name='Events',
                                                     name=event)[0]
            new_request.save()
            print "saved"
            return render_to_response('finance/budget_portal.html',
                                      locals(),
                                      context_instance=global_context(request))
    return render_to_response('finance/budget_portal.html',
                              locals(),
                              context_instance=global_context(request))
Ejemplo n.º 26
0
def eventcoord(request,event="",request_id=-1,owner_name=None,Edit=False):
    """
    Function called when an event coord logs in. Displays his requests.
    Allows him to add new requests for his event.
    Each event has a separate page
    """
    
    event_name = event
    event_coord = True
    user = request.user
    coordinating = Group.objects.filter(label__name = 'Events', members = user)
    page_owner = get_page_owner (request, owner_name)    
    
    for item in coordinating:
        if event in str(item.name):
            allow_adding_request = True
    Form = BudgetFormEvent
    if str(user.get_profile().get_dept ()) == "Finance":
        finance_coord=True
        allow_adding_request = True
        all_events_data = get_all_events()
        all_department_data = get_all_departments()
        Form = BudgetFormCoordEvent
    else:
        finance_coord=False
    if (str(user) != str(page_owner)):
        allow_adding_request = False
    if event == "":
        event_list = []
        for item in coordinating:
            
            event_list.append(item.name)
        return render_to_response('finance/select_event.html',locals(), context_instance = global_context (request))        
    finance_form = Form()
    advance_portal_finance_data = get_all_eventsadvanceportal()
    # Get requests created by an event
    self_requests = Budget_Event.objects.filter(event = Group.objects.filter(label__name = 'Events', name = event))
    accepted_requests_A = Budget_Event.objects.filter(event = Group.objects.filter(label__name = 'Events', name = event), status='A')
    required_items = Budget_Event.objects.filter(event=Group.objects.get (label__name = 'Event',
name = event))
    advance_payment_objs = []
    for item in accepted_requests_A:
        advance_payment_objs += Advance_Payment.objects.filter(link = item, finance_approval=True)

    total_budget, balance_budget_total = calculate_budget(accepted_requests_A, advance_payment_objs)
    
    accepted_requests_A_list = accepted_requests_A.values_list('id', 'amount_revised')
    string_r_A = {}
    status_A = {}
    form_tuple = []
    ids_A = []
    try:
        buffer_exist = Buffer.objects.get(event=Group.objects.get (label__name = 'Event',
name = event))
        if buffer_exist.finance_approval == True:
            buffer_approved=True
    except:
        pass
    for i in range(0, len(accepted_requests_A_list)):
        # Get data to be displayed on advance payment portal
        all_approved_requests = Advance_Payment.objects.filter(link=Budget_Event.objects.get(id=accepted_requests_A_list[i][0]), finance_approval=True)
        balance_budget = accepted_requests_A_list[i][1] - sum([x[0] for x in all_approved_requests.values_list('amount_request')])
        not_approved_objs = Advance_Payment.objects.filter(link=Budget_Event.objects.get(id=accepted_requests_A_list[i][0]), finance_approval=False)
        all_objs_for_item = Advance_Payment.objects.filter(link=Budget_Event.objects.get(id=accepted_requests_A_list[i][0]))
        not_approved_amt = sum([x[0] for x in not_approved_objs.values_list('amount_request')])
        temp = []
        ids_A.append(accepted_requests_A_list[i][0])
#        money[accepted_requests_A_list[i][0]] = AdvancePortalForm(prefix=str(accepted_requests_A_list[i][0]))
        money = AdvancePortalForm(prefix=str(accepted_requests_A_list[i][0]))

        boolformfin = BoolForm(prefix=str(accepted_requests_A_list[i][0])+"fin")
        boolformeven = BoolForm(prefix=str(accepted_requests_A_list[i][0])+"even")        
        temp.append(accepted_requests_A[i])
        temp.append(money)

        try:
            filteritem = Budget_Event.objects.get(id=accepted_requests_A_list[i][0])
            exist = Advance_Payment.objects.get(link=filteritem)
            Advance_object = exist
        except:
            exist = Advance_Payment(amount_request=0, link=filteritem)
        try:
            if exist:
                status_A = accepted_requests_A_list[i][1] - exist.amount_request
            else:
                status_A = accepted_requests_A_list[i][1]
        except:
            pass
        temp.append(status_A)
        try:
            temp.append(exist.amount_request)
        except:
            temp.append(0)
        if (is_core(user) and finance_coord):
            d = {}            
            user_is_core = True
            try:
                if(exist.finance_approval == False):
                    temp.append(boolformfin)
                else:
                    d['bool_val']="Approved"                    
                    temp.append(d)
                    d = {}
                    
                if(exist.events_approval == False):
                    d['bool_val']="Not yet Approved"                    
                    temp.append(d)
                    d = {}                    
                    
                else:
                    d['bool_val']="Approved"                                        
                    temp.append(d)
                    d = {}                    
            except:
                temp.append(boolformfin)
                d['bool_val']="Not yet Approved"                
                temp.append(d)
                d = {}                

        elif (is_core(user)):
            d = {}
            user_is_core = True
            try:
                if(exist.finance_approval == False):
                    d['bool_val']="Not yet Approved"
                    temp.append(d)
                    d = {}                    
                else:
                    d['bool_val']="Approved"
                    temp.append(d)
                    d = {}                                        
                if (exist.events_approval == False):
                    temp.append(boolformeven)                
                else:
                    d['bool_val']="Approved"                    
                    temp.append(d)
                    d = {}                    
            except:
                temp.append("Not yet Approved")
                temp.append(boolformeven)
        else:
            d = {}
            if(exist.finance_approval == False):
                d['bool_val']="Not yet Approved"                                    
                temp.append(d)
                d = {}                                    
            else:
                d['bool_val']="Approved"                                    
                temp.append(d)
                d = {}                                    
            if (exist.events_approval == False):
                d['bool_val']="Not yet Approved"                                                    
                temp.append(d)
                d = {}                                    
            else:
                d['bool_val']="Approved"                                    
                temp.append(d)
                d = {}
        now = datetime.date.today()
        due = filteritem.requirement_date
        try:
            if Advance_object.finance_approval:
                temp.append("Accepted")
            else:
                temp.append("Available")
            Advance_object = []
        except:
            if (now > due):
                temp.append("Rejected")
            else:
                temp.append("Available")
            
        temp.append(not_approved_amt)

        temp3 = []
        for item in all_objs_for_item:
            temp2 = []
            temp2.append(item)
            if item.finance_approval == True:
                dicta = {}
                dicta['bool_val'] = "Approved"
                temp2.append(dicta)
            else:
                if (is_core(user)):
                    temp2.append( BoolForm(prefix=str(item.id)))
                else:
                    dicta = {}
                    dicta['bool_val'] = "Not Approved"
                    temp2.append(dicta)
            if (item.finance_approval == True):
                temp2.append("Accepted")
            elif (now > due):
                temp2.append("Rejected")
            else:
                temp2.append("Available")
            temp3.append(temp2)
        temp.append(temp3)
        temp.append(balance_budget)
        form_tuple.append(temp)
        
    temp = []
    # For Buffer in Advance payment Portal
    bufferform = []
    bufferform.append(BufferForm())
    # For Buffer
    temp = []
    buffer_A = []
    try:
        exist = Buffer.objects.get(event=Group.objects.get (label__name = 'Event',
name = event))
    except:
        exist = Buffer(event=Group.objects.get (label__name = 'Event',
name = event))	
    buffer_A = []
    buffer_A.append(exist)
    # If core, then allow him to approve requests.
    if (is_core(user) and finance_coord):
        d = {}            
        user_is_core = True
        try:
            if(exist.finance_approval == False):
                temp.append(BoolForm(prefix=str("bufferfin")))                                    
            else:
                d['bool_val']="Approved"                    
                temp.append(d)
                d = {}                                        
            if(exist.events_approval == False):
                d['bool_val']="Not yet Approved"                    
                temp.append(d)
                d = {}                                        
            else:
                d['bool_val']="Approved"                                        
                temp.append(d)
                d = {}                                        
        except:
            temp.append(boolformfin)
            d['bool_val']="Not yet Approved"                
            temp.append(d)
    elif (is_core(user)):
        d = {}
        user_is_core = True
        try:
            if(exist.finance_approval == False):
                d['bool_val']="Not yet Approved"
                temp.append(d)
                d = {}                                        
            else:
                d['bool_val']="Approved"                    
                temp.append(d)
                d = {}                                        
            if (exist.events_approval == False):
                temp.append(BoolForm(prefix=str("buffereven")))                
            else:
                d['bool_val']="Approved"                    
                temp.append(d)
                d = {}                                        
        except:
            temp.append("Not yet Approved")
            temp.append(BoolForm(prefix=str("buffereven")))                                                
    else:
        d = {}
        if(exist.finance_approval == False):
            d['bool_val']="Not yet Approved"                                    
            temp.append(d)
            d = {}                                                        
        else:
            d['bool_val']="Approved"                                    
            temp.append(d)
            d = {}                                                        
        if (exist.events_approval == False):
            d['bool_val']="Not yet Approved"                                                    
            temp.append(d)
            d = {}                                                        
        else:
            d['bool_val']="Approved"                                    
            temp.append(d)
            d = {}


# Amount Requested

            
    buffer_A.append(temp)
    sum_amount_a,sum_amount_b,sum_amount_r = calculate_sums(self_requests)    

    if request_id >= 0:
        request_to_edit = Budget_Event.objects.get (id = request_id)
        Edit = True
        finance_form = Form(initial={'particular':request_to_edit.particular, 'requirement_date':request_to_edit.requirement_date, 'amount_a':request_to_edit.amount_a, 'amount_b':request_to_edit.amount_b, 'amount_revised':request_to_edit.amount_revised, 'status':request_to_edit.status})
        if request.method == 'POST':        
            finance_form = Form(request.POST)
            if finance_form.is_valid():
                request_to_edit.particular = finance_form.cleaned_data['particular']
                request_to_edit.requirement_date = finance_form.cleaned_data['requirement_date']
                request_to_edit.amount_a = finance_form.cleaned_data['amount_a']
                request_to_edit.amount_b = finance_form.cleaned_data['amount_b']
                success = True
                if finance_coord:
                    request_to_edit.amount_revised = finance_form.cleaned_data['amount_revised']
                    request_to_edit.status = finance_form.cleaned_data['status']                    
                request_to_edit.save()
                request_id = -1
                return HttpResponseRedirect("./")
        return render_to_response('finance/budget_portal.html',locals(), context_instance = global_context (request))
#    return redirect ('finance.views.finance', locals())
    print "nearing"
    if request.method == 'POST':
        finance_form = Form(request.POST)
        print "saving"
        if finance_form.is_valid():
            new_request = finance_form.save (commit = False)
            success = True
            new_request.requester = user
            if not new_request.amount_revised:
                new_request.amount_revised = 0            
            new_request.event = Group.objects.filter(label__name = 'Events', name = event)[0]
            new_request.save()
            print "saved"
            return render_to_response('finance/budget_portal.html',locals(), context_instance = global_context (request))
    return render_to_response('finance/budget_portal.html',locals(), context_instance = global_context (request))