def forgot_password(request,email=None):
    dajax = Dajax()
    if not email is None and not email == '' :
        try:
            validate_email(email)
#            validate_email is a django inbuilt function that throws ValidationError for wrong email address
#            Issue: starts with _ not acceptable
            profile = UserProfile.objects.get(user__email = str(email))
            email = profile.user.email
            user = profile.user
            if not profile.user.is_active:
                dajax.script('$.bootstrapGrowl("Activate your account first! Check your mail for the activation link." , {type:"error",delay:20000} );')
                return dajax.json()
            mail_template = get_template('email/forgot_password.html')
            body = mail_template.render( Context( {
                    'username':user.username,
                    'SITE_URL':settings.SITE_URL,
                    'passwordkey':profile.activation_key,
                }))
            #if settings.SEND_EMAILS:
            send_mail('Shaastra2014 password reset request', body,'*****@*****.**', [user.email,], fail_silently=False)
            dajax.script('$.bootstrapGrowl("An email with a link to reset your password has been sent to your email id: %s", {type:"success",delay:20000} );' % email)
            dajax.script('$.bootstrapGrowl("Please also check your spam", {type:"danger",delay:20000});')
        except ValidationError:
            dajax.script('$.bootstrapGrowl("Your email:%s is invalid", {type:"danger",delay:10000} );' % email)
            return dajax.json()
        except:
            dajax.script('$.bootstrapGrowl("Not a registered email id", {type:"danger",delay:20000} );')
            return dajax.json()
    return dajax.json()
def show_event_tdp(request,teamevent_id=None):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")    
    if teamevent_id is None:
        dajax.script('$.bootstrapGrowl("Invalid request to view teamevent details", {type:"danger",delay:20000} );')
        return dajax.json()
    try:
        temp = int(teamevent_id)
    except:
        dajax.script('$.bootstrapGrowl("Invalid request to view teamevent details", {type:"danger",delay:20000} );')
        return dajax.json()
    if not request.user.is_authenticated():
        dajax.script('$.bootstrapGrowl("Login to view your event submission details", {type:"danger",delay:20000} );')
        return dajax.json()
    else:
        profile = UserProfile.objects.get(user=request.user)
        try:
            team_event = TeamEvent.objects.get(id=int(teamevent_id))
        except:
            dajax.script('$.bootstrapGrowl("Invalid request", {type:"danger",delay:20000} );')
            return dajax.json()
        now = timezone.now()
        context_dict = {'teamevent':team_event,'profile':profile,'now':now,'TDPFileForm':TDPFileForm(),'settings':settings}
        
        html_stuff = render_to_string('dashboard/event_tdp_submit.html',context_dict,RequestContext(request))
        if html_stuff:
            dajax.assign('#content_dash','innerHTML',html_stuff)
            #dajax.script('$("#event_register").modal("show");')
    return dajax.json()
Example #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()
Example #4
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()
def logout(request,**kwargs):
    dajax = Dajax()
    auth_logout(request)
    dajax.script('$.bootstrapGrowl("Successfully logged out!", {type:"success",delay:10000});' )
    dajax.assign("#login_logout", "innerHTML", '<a href="#login" onclick="$(\'#login\').modal(\'show\');">Login | Sign Up </a>')
    dajax.add_css_class("#dashboard","hide hidden")
    dajax.script("window.location.hash = 'events';")
    return dajax.json()
Example #6
0
def test_dajax(request):
    """
        Simple function to rest (D)ajax(ice)
    """
    dajax = Dajax() # To hold the json
    dajax.script('alert(\'hello\');');
    dajax.script( '$("#container_messages").append(\'<div class="span8 offset2"><div class="alert ' + 'alert-success' + ' center"><button type="button" class="close" data-dismiss="alert"><i class="icon-close">&times;</i></button>' + 'This is a test script! No need to listen to me.' + ' </div></div><div class="offset2"></div>\')' )
    return dajax.json()
Example #7
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()
def back(request):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")    
    no_regd = len(request.user.get_profile().get_regd_events())
    reco_events = ParticipantEvent.objects.using(erp_db).filter(registrable_online=True)
#    reco_events = registrable_events(time = timezone.now(),user = request.user)
    context_dict = {'profile':request.user.get_profile(),'no_regd':no_regd,'reco_events':reco_events}
    html_stuff = render_to_string('dashboard/default.html',context_dict,RequestContext(request))
    if html_stuff:
        dajax.assign('#content_dash','innerHTML',html_stuff)
    return dajax.json()
def add_member_form(request,teamevent_id = None):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")
    if teamevent_id is None:
        return dajax.json()
    try:
        teamevent = TeamEvent.objects.get(id = teamevent_id)
    except:
        return dajax.json()
    html_stuff = render_to_string('dashboard/add_member.html',{'teamevent':teamevent},RequestContext(request))
    if html_stuff:
        dajax.assign('#content_dash','innerHTML',html_stuff)
    return dajax.json()
Example #10
0
def test_dajax(request):
    """
        Simple function to rest (D)ajax(ice)
    """
    dajax = Dajax()  # To hold the json
    dajax.script('alert(\'hello\');')
    dajax.script(
        '$("#container_messages").append(\'<div class="span8 offset2"><div class="alert '
        + 'alert-success' +
        ' center"><button type="button" class="close" data-dismiss="alert"><i class="icon-close">&times;</i></button>'
        + 'This is a test script! No need to listen to me.' +
        ' </div></div><div class="offset2"></div>\')')
    return dajax.json()
def show_tdp_submissions(request):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")
    if not request.user.is_authenticated():
        dajax.script('$.bootstrapGrowl("Login to view your registered events", {type:"danger",delay:20000} );')
        return dajax.json()
    else:
        profile = UserProfile.objects.get(user=request.user)
        team_event_list = profile.get_regd_events()
        tdp_submission_list = []
        for teamevent in team_event_list:
            if teamevent.get_event().has_tdp and teamevent.has_submitted_tdp:
                tdp_submission_list.append(teamevent)
        no_regd = len(tdp_submission_list)
        now = timezone.now()
        title_tdp = 'Your successful TDP Submissions'
        context_dict = {'tdp_submission_list':tdp_submission_list,'profile':profile,'now':now,'no_regd':no_regd,'settings':settings,'title_tdp':title_tdp}
        html_stuff = render_to_string('dashboard/list_tdp_submission.html',context_dict,RequestContext(request))
        if html_stuff:
            dajax.assign('#content_dash','innerHTML',html_stuff)
            #dajax.script('$("#event_register").modal("show");')
    msg_file_upload = request.session.get('file_upload','')
    if msg_file_upload != '':
        del request.session['file_upload']
        print msg_file_upload
        print str(msg_file_upload).startswith('TDP Upload Successful') 
        if str(msg_file_upload).startswith('TDP Upload Successful'):
            dajax.script('$.bootstrapGrowl("%s", {type:"success",delay:20000} );'% msg_file_upload)
        else:
            dajax.script('$.bootstrapGrowl("FileUpload Error: %s", {type:"danger",delay:20000} );'% msg_file_upload)
    return dajax.json()
def change_password_form(request):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")
    #: if user has chosen a college in dropdown, depopulate it OR growl
    if not request.user.is_authenticated():
        dajax.script('$.bootstrapGrowl("Login First!", {type:"danger",delay:10000} );')
        return dajax.json()
    profile = UserProfile.objects.get(user=request.user)
    change_password_form = ChangePasswordForm()
    context_dict = {'form_change_password':change_password_form,'profile':profile,'settings':settings}
    html_stuff = render_to_string('dashboard/change_password.html',context_dict,RequestContext(request))
    if html_stuff:
        dajax.assign('#content_dash','innerHTML',html_stuff)
        #dajax.script('$("#event_register").modal("show");')
    return dajax.json()
def show_updates(request):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")
    if not request.user.is_authenticated():
        dajax.script('$.bootstrapGrowl("Login to view your registered events", {type:"danger",delay:20000} );')
        return dajax.json()
    else:
        profile = request.user.get_profile()
        updates_list = list(Update.objects.filter(user = request.user).order_by('tag'))
        #TODO: order by time??: 
        no_updates = len(updates_list)
        now = timezone.now()
        context_dict = {'updates_list':updates_list,'profile':profile,'now':now,'no_updates':no_updates,'settings':settings}
        html_stuff = render_to_string('dashboard/list_updates.html',context_dict,RequestContext(request))
        if html_stuff:
            dajax.assign('#content_dash','innerHTML',html_stuff)
            #dajax.script('$("#event_register").modal("show");')
    return dajax.json()
Example #14
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()
def edit_profile(request,form = None,first_name = None,last_name = None):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")
    if form is None or first_name is None or last_name is None:
        dajax.script('$.bootstrapGrowl("Invalid edit profile request", {type:"danger",delay:20000} );')
        return dajax.json()
    if first_name == '' or last_name == '':
        dajax.script('$.bootstrapGrowl("Empty first name/last name fields not allowed", {type:"danger",delay:20000} );')
        return dajax.json()
    form = EditProfileForm(deserialize_form(form))
    if not form.is_valid():
        errdict = dict(form.errors)
        for error in form.errors:
#            if str(errdict[error][0])!='This field is required.':
            dajax.script('$.bootstrapGrowl("%s:: %s" , {type:"error",delay:20000} );'% (str(error),str(errdict[error][0])))
        return dajax.json()
    profile = UserProfile.objects.get(user=request.user)
    (profile.branch,profile.mobile_number,profile.college_roll,profile.gender,profile.age)  = (form.cleaned_data['branch'],form.cleaned_data['mobile_number'],form.cleaned_data['college_roll'],form.cleaned_data['gender'],form.cleaned_data['age'])
    profile.user.first_name = first_name
    profile.user.last_name = last_name
    profile.save()
    dajax.script('$.bootstrapGrowl("Your profile has been edited" , {type:"success",delay:10000,align:"center",width:"auto"} );')
    return dajax.json()
def submit_tdp(request,teamevent_id = None,file_tdp=None):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")        
    if teamevent_id is None or file_tdp is None:
        dajax.script('$.bootstrapGrowl("Invalid TDP Upload request", {type:"danger",delay:20000} );')
        return dajax.json()
    team_event =TeamEvent.objects.get(id = teamevent_id)
    if len(request.FILES) == 0:
        dajax.script('$.bootstrapGrowl("Please upload a file first!", {type:"danger",delay:20000} );')
    fileform = TDPFileForm(deserialize_form(file_tdp),request.FILES)

    try:
        event = teamevent.get_event()
        tdp = TDP(tdp=fileform,teamevent = teamevent)
        tdp.save()
    except:
        print
    return dajax.json()
Example #17
0
def password_reset(request, username=None, email=None):
    """
        Generates a one-use only link for resetting password and sends to the user.
    """
    from django.utils.http import urlsafe_base64_encode
    from django.core.mail import send_mail
    from django.contrib.sites.models import get_current_site
    from django.utils.encoding import force_bytes
    from django.contrib.auth.tokens import default_token_generator

    dajax = Dajax()  # To hold the json
    if username:
        active_users = User.objects.filter(username__iexact=username,
                                           is_active=True)
        count = 0
        for user in active_users:
            if not user.has_usable_password():
                continue
            c = {
                'email': user.email,
                'site_url': settings.SITE_URL,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': default_token_generator.make_token(user),
                'protocol': 'http',
            }
            subject = 'NSS-IITM Password Reset Request'
            email = render_to_string('emails/password_reset.html', c)
            ret_val = send_mail(subject, email, settings.DEFAULT_FROM_EMAIL,
                                [user.email])
            print ret_val
            count = count + 1
        print count, "emails sent !"
        if count:
            dajax.script('alert(\'Username sent!\')')  # To hold the json
        else:
            dajax.script('alert(\'Username not found!\')')  # To hold the json
    else:
        dajax.script('alert(\'Please enter a username !\')')
    return dajax.json()
Example #18
0
def password_reset(request, username=None, email=None):
    """
        Generates a one-use only link for resetting password and sends to the user.
    """
    from django.utils.http import urlsafe_base64_encode
    from django.core.mail import send_mail
    from django.contrib.sites.models import get_current_site
    from django.utils.encoding import force_bytes
    from django.contrib.auth.tokens import default_token_generator
    
    dajax = Dajax() # To hold the json
    if username:
        active_users = User.objects.filter(username__iexact=username, is_active=True)
        count = 0
        for user in active_users:
            if not user.has_usable_password():
                continue
            c = {
                'email': user.email,
                'site_url': settings.SITE_URL,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': default_token_generator.make_token(user),
                'protocol': 'http',
            }
            subject = 'NSS-IITM Password Reset Request'
            email = render_to_string('emails/password_reset.html', c)
            ret_val = send_mail(subject, email, settings.DEFAULT_FROM_EMAIL, [user.email])
            print ret_val
            count = count + 1;
        print count, "emails sent !"
        if count:
            dajax.script('alert(\'Username sent!\')') # To hold the json
        else:
            dajax.script('alert(\'Username not found!\')') # To hold the json
    else:
        dajax.script('alert(\'Please enter a username !\')')
    return dajax.json()
def add_college(request,college=None,city=None,state=None):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")    
    #: if user has chosen a college in dropdown, depopulate it OR growl
    if city is None or college is None or state is None or city =='' or college =='' or state =='':
        dajax.script('$.bootstrapGrowl("Please enter relevant details for adding your college", {type:"danger",delay:10000});')
        return dajax.json()
    else:
        try:
            College.objects.get(name__iexact=college)
            dajax.script('$.bootstrapGrowl("Your college is already on our list, please check again", {type:"danger",delay:10000});')
            return dajax.json()
        except:
            coll=None
        dajax.script('$("#add_college").modal(\'hide\');')
        dajax.script('$("#login").show();')
        coll=College(name=college,city=city,state=state)
        try:
            if clean_coll(coll.name) and clean_coll(coll.city):
                coll.save()
            else:
                dajax.script('$.bootstrapGrowl("Please refrain from using profanity", {type:"danger",delay:10000});')
                return dajax.json()
        except:
            coll.save()
        dajax.assign("#add_coll_name",'innerHTML','%s'% college)
        dajax.assign("#add_coll_result",'innerHTML','College:')
        #dajax.script("$('#college')[0]value = '%s'" % college)
        dajax.script('$.bootstrapGrowl("Your college:<strong>%s</strong> was added. Welcome", {type:"success",delay:10000} );'% str(coll.name) )
        # : populate the id_college with the given college details?
        dajax.script("$('#add_coll_message').toggle();")
        dajax.script("$('#form_registration #id_college').toggle();")
        dajax.script("$('#add_coll_form').toggle();")
#    colllist=College.objects.all()
    return dajax.json()
def login(request,login_form = None):
    dajax = Dajax()
    if request.user.is_authenticated():
        msg_login='******' % request.user.username
        dajax.script('$.bootstrapGrowl("%s", {type:"danger",delay:20000} );'% msg_login )
        dajax.script('$(".modal-header").find(".close").click()')
        return dajax.json()
    elif request.method == 'POST' or login_form != None:
        form = LoginForm(deserialize_form(login_form))
        if form.is_valid() :
            data=form.cleaned_data
            username=data['username']
            password=data['password']
            user = authenticate(username=username, password=password)
            if user:
                if not user.is_active:
                    msg = 'Please click the activation link sent to your registered email id to activate your account'
                    dajax.script('$.bootstrapGrowl("%s", {type:"danger",delay:30000} );' % msg)
                    dajax.script("$('#login_form #id_password').val('');")
                    return dajax.json()
                auth_login(request, user)
                dajax.script('$.bootstrapGrowl("Hi %s" , {type:"success",delay:10000} );'% user.username )
                dajax.script("$('#login_form #id_password').val('');")
                dajax.script("$('#login').modal('hide');")
                dajax.script('$(".modal-header").find(".close").click()')
                dajax.script('$("#fb_share").modal("show");')
                profile = UserProfile.objects.get(user=request.user)
                context_dash_dict = {'profile':profile,'settings':settings}
                html_stuff = render_to_string('dashboard/welcome.html',context_dash_dict,RequestContext(request))
                dajax.script("window.location.hash = 'dashboard'")
                if html_stuff:
                    dajax.assign('#content_dash','innerHTML',html_stuff)
#                dajax.script('$(\"#list_user_head a\").click();')
                #dajax.script('$(\"#list_events_head a\").click();')
                #dajax.script('javascript:do_accordion(\"list_user\");')
#                dajax.script("javascript:do_accordion('list_user')")
                
                dajax.script("$('#aboutus').hide();")
                dajax.assign("#dashboard #dashboard_shaastra_id","innerHTML",str(request.user.get_profile().shaastra_id))
                dajax.assign("#dashboard #dashboard_full_name","innerHTML",str(request.user.get_full_name()))
                dajax.assign("#login_logout", "innerHTML",'<div class="btn-group">\
                <button class="btn" onclick ="window.location.replace(\'#dashboard\');\
                "><i class="icon-user icon-white"></i>My Dashboard&nbsp;&nbsp;\
                </button></div>')
                dajax.remove_css_class("#dashboard","hide hidden")
                #display logout| edit profile on navbar
                return dajax.json()
            else:
                msg = 'Username and Password does not match!!!'
                if User.objects.filter(username=username).count()==0:
                    msg = 'Username not created, did you want to register?'
                dajax.script('$.bootstrapGrowl("%s", {type:"danger",delay:20000} );' % msg)
                dajax.script("$('#login_form #id_password').val('');")
                form = LoginForm()
                form_registration = AddUserForm()
                return dajax.json()
        else:
            dajax.remove_css_class('#my_form input', 'error')
            for error in form.errors:
                dajax.add_css_class('#login_form #id_%s' % error, 'error')
            return dajax.json()
            #Code for error rendering
    else:
        dajax.script('$.bootstrapGrowl("Fill in required details", {type:"danger",delay:20000} );')
        #empty form case
        return dajax.json()
    return dajax.json()
def register(request,form_registration=None,college_name=None):
    #logged in user cannot register, but just in case
    dajax = Dajax()
    college = None
    new_coll = False
    if not college_name is None:
        try:
            college=College.objects.filter(name=str(college_name))[0]
            new_coll = True
        except:
            #impossible scenario!!
            dajax.script("$.bootstrapGrowl('You must have entered your college first!', {type:'danger',delay:10000});")
            dajax.script('$("#gif_registration").hide();$("#form_registration_submit").show()')
    
            return dajax.json()
    
    if request.user.is_authenticated():
        msg_login = '******' % request.user.username
        dajax.script('$.bootstrapGrowl("Hi %s" , {type:"danger",delay:10000} );'% msg_login )
        dajax.script('$("#gif_registration").hide();$("#form_registration_submit").show()')
    
        return dajax.json()
        
    if request.method=="POST" and (form_registration !=None or not college_name is None):
        form = AddUserForm(deserialize_form(form_registration))
        if form.is_valid():
            #TODO: if we change college to be a compulsory, then this must be changed
            dajax.remove_css_class('#form_registration input', 'error')
            data = form.cleaned_data
            new_user = User(first_name=data['first_name'],last_name=data['last_name'], username=data['username'], email=data['email'])
            new_user.set_password(data['password']) 
            new_user.save()
            new_user.is_active = True
            new_user.save()
            x = 1400000 + new_user.id 
            salt = sha.new(str(random.random())).hexdigest()[:5]
            activation_key = sha.new(salt + new_user.username).hexdigest()
            if college is None:
                userprofile = UserProfile(user=new_user,activation_key=activation_key,gender=data['gender'],age=data['age'],branch=data['branch'],mobile_number=data['mobile_number'],college=data['college'],college_roll=data['college_roll'],shaastra_id= ("SHA" + str(x)),key_expires = timezone.now()+datetime.timedelta(2))
            else:
                userprofile = UserProfile(user=new_user,activation_key=activation_key,gender=data['gender'],age=data['age'],branch=data['branch'],mobile_number=data['mobile_number'],college=college,college_roll=data['college_roll'],shaastra_id= ("SHA" + str(x)),key_expires = timezone.now()+datetime.timedelta(2))
            userprofile.save()
            #mail_template = get_template('email/activate.html')
            #body = mail_template.render( Context( {
            #        'username':new_user.username,
            #        'activationkey':userprofile.activation_key,
            #        'SITE_URL':settings.SITE_URL,
            #        'shaastra_id':userprofile.shaastra_id,
            #    }))
            #TODO: empty the entire form!!
            #dajax.script("$('#form_registration').val('');")\
            #dajax.script("$('#form_registration #id_email').val('');\
            #             $('#form_registration #id_password').val('');\
            #             $('#form_registration #id_password_again').val('');\
            #             $('#form_registration #id_mobile_number').val('');")
            #if settings.SEND_EMAILS:
            #subject, from_email, to = 'Your new Shaastra2014 account confirmation', '*****@*****.**', [new_user.email,]
            #html_content = body
            #text_content = strip_tags(body)
            
            #msg = EmailMultiAlternatives(subject, text_content, from_email, to)
            #msg.attach_alternative(html_content, "text/html")
            
            #msg.send()
            
            #send_mail('Your new Shaastra2014 account confirmation', body,'*****@*****.**', [new_user.email,], fail_silently=False)
            #msg='Hi, A mail has been sent to the mail id you provided. Please activate your account within 48 hours. Please also check your spam folder'
            msg = 'Successfully Registered ! <br /> Welcome !'
#            dajax.script('$(".modal-header").find(".close").click();')
            dajax.script('$.bootstrapGrowl("%s" , {type:"success",delay:20000} );'% msg )
            dajax.script('$("#gif_registration").hide();$("#form_registration_submit").show();$("#login").modal("hide")')
            dajax.script('$("#form_registration #id_college_roll").attr("readonly", false);$("#form_registration #id_college_roll").val("");')
            return dajax.json()
        else:
            errdict=dict(form.errors)
            dajax.script('$.bootstrapGrowl("Oops : Following errors cropped up when you tried to register !", {type:"danger",timeout:50000} );')
            for error in form.errors:
                if str(errdict[error][0])!='This field is required.':
                    dajax.script('$.bootstrapGrowl(" %s" , {type:"error",delay:20000} );'% str(errdict[error][0]))
            dajax.script("$('#form_registration #id_password').val('');")
            dajax.script("$('#form_registration #id_password_again').val('');")
            for error in form.errors:
                dajax.add_css_class('#form_registration #id_%s' % error, 'error')
            dajax.script('$("#gif_registration").hide();$("#form_registration_submit").show()')
            return dajax.json()
    if request.method == 'GET':
        form_registration = AddUserForm()
        dajax.script('$("#gif_registration").hide();$("#form_registration_submit").show()')
        return dajax.json()
    form_registration=AddUserForm()
    dajax.script('$("#gif_registration").hide();$("#form_registration_submit").show()')
    return dajax.json()
def remove_member(request,user_id = None,teamevent_id = None):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")
    if not request.user.is_authenticated():
        dajax.script('$.bootstrapGrowl("Login First",{type:"danger",delay:10000})')
        return dajax.json()
    if teamevent_id is None or user_id is None:
        dajax.script('$.bootstrapGrowl("Invalid request",{type:"danger",delay:10000})')
        return dajax.json()
    try:
        teamevent = TeamEvent.objects.get(id = teamevent_id)
        user = User.objects.get(id = user_id)
        if user not in teamevent.users.all() or request.user not in teamevent.users.all():
            dajax.script('$.bootstrapGrowl("Invalid request: user not part of team",{type:"danger",delay:10000})')
            #Malicious attempt!?
            return dajax.json()
        if teamevent.size() == teamevent.get_event().team_size_min:
            dajax.script('$.bootstrapGrowl("Sorry. Remove failed.You cannot have less than %s team members",{type:"danger",delay:10000})'% teamevent.get_event().team_size_min)
            return dajax.json()
        teamevent.users.remove(user)
        teamevent.save()
        msg_update = 'Your teammate %s was removed from team %s for event %s on %s by %s'%(user.get_full_name(),teamevent.team_name,str(timezone.now()),request.user.get_full_name())
        for user_team in teamevent.users.all():
            update = Update(tag = 'Team Edit',content = msg_update,user = user_team)
            update.save()
        msg_update_user = '******'%(teamevent.team_name,teamevent.get_event().title,str(timezone.now()),request.user.get_full_name())
        update = Update(tag = 'Team Remove',content = msg_update_user,user = user)
        update.save()
        dajax.script('$.bootstrapGrowl("Removal succesrs! %s is no longer a member of team %s",{type:"info",delay:10000,width:"auto"})'% (user.get_full_name(),teamevent.team_name))
        #TODO: Update create
        msg_dash = "Removal success! %s is no longer a member of team %s"% (user.get_full_name(),teamevent.team_name)
        html_stuff = render_to_string('dashboard/welcome.html',{'msg_dash':msg_dash},RequestContext(request))
        if html_stuff:
            dajax.assign('#content_dash','innerHTML',html_stuff)
    
        return dajax.json()
    except:
        dajax.script('$.bootstrapGrowl("Invalid request. ",{type:"danger",delay:10000})')    
        return dajax.json()
    return dajax.json()
def register_event_form(request,event_id = None):
    dajax = Dajax()
    #dajax.script("$('#gif_eventregister').hide()")
    #: if user has chosen a college in dropdown, depopulate it OR growl
    if event_id is None:
        dajax.script('$.bootstrapGrowl("Invalid Event specified.", {type:"danger",delay:10000} );')
        return dajax.json()
    else:
        try:
            erp_db = DATABASES.keys()[1]
            event = ParticipantEvent.objects.using(erp_db).get(id=event_id)
            if not request.user.is_authenticated():
                #dajax.script('$.bootstrapGrowl("Please Login to register!", {delay:10000,ele:"#events",width:"auto"} );')
                dajax.script('$.bootstrapGrowl("Please Login to register for the event!", {delay:10000,type:"danger"} );')
                html_stuff = render_to_string('dashboard/event_regd_message.html',{},RequestContext(request))
                dajax.assign('#FormRegd','innerHTML',html_stuff)
                dajax.script('$("#event_register").modal();')

                #dajax.script('$("#login").modal();')
                return dajax.json()
            user = request.user
        except:
            dajax.script('$.bootstrapGrowl("Invalid Event specified", {type:"danger",delay:20000} );')
            return dajax.json()
        if not event.registrable_online:
            dajax.script('$.bootstrapGrowl("You cannot register online for the event:%s", {type:"danger",delay:50000} );'% event.title)
            return dajax.json()
        elif event.registration_starts and event.registration_ends:
            if event.registration_starts > timezone.now():
                days = (event.registration_starts - timezone.now()).days
                dajax.script('$.bootstrapGrowl("Please wait until %d days for registrations to open for %s", {type:"danger",delay:10000} );' % (days,event.title))
                return dajax.json()
            elif event.registration_ends < timezone.now():
                dajax.script('$.bootstrapGrowl("Registrations closed for %s! Sorry", {type:"danger",delay:20000,width:"auto",align:"center"} );'% event.title)
                return dajax.json()
            else:
                maxteam = event.team_size_max
                minteam = event.team_size_min
#                maxteam=3
#                minteam=3
                if maxteam >1:
                    msg,team_name = has_team(request.user,event.id)
                    if msg =='has_team':
                        dajax.script('$.bootstrapGrowl("You are already a part of team:%s for this event. Multiple entries for same user is not allowed sorry", {delay:10000})'% str(team_name))
                        #TODO: close the 
                        return dajax.json()
                    if event.team_size_min>1:
                        dajax.script('$.bootstrapGrowl("Note that you need to have a team with atleast %d more members to register", {delay:100000} );'% (event.team_size_min-1))
                    else:
                        dajax.script('$.bootstrapGrowl("You can register alone, or with a maximum of %d teammates", {delay:100000} );'% (event.team_size_max-1))
                    teammates = range(minteam,maxteam)
                    teammates = teammates[:-1]
                    teammates_min = range(minteam)
                    inputhtml = ""
                    for i in (teammates_min+teammates)[:len(teammates_min+teammates)]:
                        inputhtml +="\'teammate#%d\':$(\'#shid_%d\').val()," %(i+1,i+1)
                    
                    inputhtml=inputhtml[:len(inputhtml)-1]
                    
                else:
                    msg,team_name = has_team(request.user,event.id)
                    if msg =='has_team':
                        dajax.script('$.bootstrapGrowl("You are already a part of team:%s for this event. Multiple entries for same user is not allowed sorry", {delay:20000});'%team_name);
                        return dajax.json()
                    #tev = TeamEvent(event_id = event.id)
                    #tev.save()
                    #tev.users.add(request.user)
                    #tev.save()
                    #update = Update(tag='Event registration',content='Added to team: %s in event %s'%(tev.team_name,tev.get_event().title),user=request.user)
                    #update.save()
                    #dajax.script('$.bootstrapGrowl("You have been registered for %s", {timeout:100000});' %event.title );
                    #TODO: update
                    inputhtml=''
                    teammates=[]
                    teammates_min=[]
                    #dajax.script('$("#event_register").modal("toggle");')
                    #return dajax.json()
                context_dict = {'event': event,'teammates':teammates,'teammates_min':teammates_min,'inputhtml':inputhtml,'team_max':len(teammates_min+teammates)-1,'minteam':minteam}
                html_stuff = render_to_string('dashboard/event_registration_form.html',context_dict,RequestContext(request))
                if html_stuff:
                    dajax.assign('#FormRegd','innerHTML',html_stuff)
                    dajax.script('$("#event_register").modal();')
        else:
            dajax.script('$.bootstrapGrowl("Registrations not put up yet, please wait!", {delay:10000} );')
    return dajax.json()
def register_event(request,event_id=None,team_name=None,**kwargs):
    dajax=Dajax()
    if event_id is None or team_name is None:
        dajax.script('$.bootstrapGrowl("Invalid entry",{type:"danger",delay:10000})')
        return dajax.json()
    i=1
    shalist=[]
    erp_db = DATABASES.keys()[1]
    try:
        event=ParticipantEvent.objects.using(erp_db).get(id=event_id)
        if not event.registrable_online:
            dajax.script('$.bootstrapGrowl("Invalid event: can\'t register online!",{type:"danger",delay:10000})')
            #TODO: close the modal!!
            return dajax.json()
    except:
        dajax.script('$.bootstrapGrowl("Invalid event",{type:"danger",delay:10000})')    
        return dajax.json()
    teamevent = TeamEvent(event_id=event.id)
    profile = UserProfile.objects.get(user=request.user)
    sha=''
    while 1>0:
        try:
            sha = kwargs['teammate#%d' % i]
            if sha!='':
                if sha==profile.shaastra_id:
                    dajax.script('$.bootstrapGrowl("Enter your teammates\' ID\'s only. You will be registered automatically. You do no need to enter your ID",{type:"danger",delay:10000})')
                    return dajax.json()
                shalist.append(sha)
        except:
            break
        i=i+1
    #check for duplicates
    #TODO: find actual entries first(without '')
    if len(shalist)!=len(set(shalist)):
        dajax.script('$.bootstrapGrowl("No duplicate entries allowed.",{type:"danger",delay:10000})')
        return dajax.json()
    if len(shalist) < event.team_size_min-1:
        dajax.script('$.bootstrapGrowl("Minimum team size:%d!",{type:"danger",delay:10000})'% event.team_size_min)
        return dajax.json()
    msg,teamname = has_team(request.user,event.id)
    if msg =='has_team':
        dajax.script('$.bootstrapGrowl("You are already a part of another team named %s for this event.");$.bootstrapGrowl("A user can be part of only 1 team for an event",{type:"danger",delay:20000});'% (teamname))
        return dajax.json()
    userlist=[]
    userlist.append(request.user)
    up=None
    for sha in shalist:
        try:
            up = UserProfile.objects.get(shaastra_id = sha)
            msg,teamname = has_team(up.user,event.id)
            if msg =='has_team':
                dajax.script('$.bootstrapGrowl("One of your teammates: with id %s is already in another team named %s for this event.");$.bootstrapGrowl("A user can be part of only 1 team for an event",{type:"danger",delay:20000});'% (up.shaastra_id,teamname))
                return dajax.json()
            userlist.append(up.user)
        except:
            dajax.script('$.bootstrapGrowl("One/more of shaastra id\'s entered are invalid!",{type:"danger",delay:20000})')
            return dajax.json()
    teamevent.save()
    teamevent.users=userlist
    teamevent.is_active = True
    teamevent.team_name = team_name
    teamevent.save()
    try:
        for user in userlist:
            update = Update(tag='Event registration',content='Added to team: %s in event %s'%(teamevent.team_name,teamevent.get_event().title),user=user)
            update.save()
    #TODO: updates should not cause error
    except:
        pass
    dajax.script('$.bootstrapGrowl("Your team was registered successfully to event %s",{type:"success",delay:30000})'% event.title)
    dajax.script('$.bootstrapGrowl("Your team ID: %s",{type:"success",delay:100000})'% teamevent.team_id)
    dajax.script('$("#event_register").modal("toggle")')
    enddate = teamevent.get_event().registration_ends
    dajax.script('$.bootstrapGrowl("Please note the deadline for the event given in event details.", {delay:100000} );')
    dajax.script('$("#fb_share").modal("show");')
    #TODO: create updates for other users and him
    return dajax.json()
def change_password(request,form = None):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")
    if not request.user.is_authenticated():
        dajax.script('$.bootstrapGrowl("Login First!", {type:"danger",delay:10000} );')
        return dajax.json()
    
#    print deserialize_form(form)
    if form is None:
        dajax.script('$.bootstrapGrowl("Invalid password change request", {type:"danger",delay:10000} );')
        return dajax.json()
    form = ChangePasswordForm(deserialize_form(form))
    if not form.is_valid():
        errdict = dict(form.errors)
        for error in form.errors:
#            if str(errdict[error][0])!='This field is required.':
            dajax.script('$.bootstrapGrowl("%s:: %s" , {type:"error",delay:10000} );'% (str(error),str(errdict[error][0])))
        dajax.script("$(\'#form_change_password #id_new_password').val('');$('#form_change_password #id_new_password_again').val('');")
        return dajax.json()
    user = request.user
    if not user.check_password(form.cleaned_data['old_password']):
        dajax.script('$.bootstrapGrowl("Please check your old password" , {type:"error",delay:10000} );')
        return dajax.json()
    user.set_password(form.cleaned_data['new_password'])
    profile = UserProfile.objects.get(user=request.user)
    
    user.save()
    profile.save()
    dajax.script('$.bootstrapGrowl("Your password was changed successfully!" , {type:"success",delay:30000} );')
    #TODO: why is the field not getting empty?????
    dajax.script('$("#dashboard #form_change_password #id_old_password").val("");')
    dajax.script('$("#dashboard #form_change_password #id_new_password").val("");')
    dajax.script('$("#dashboard #form_change_password #id_new_password_again").val("");')
    
    return dajax.json()
def add_member(request,shaastra_id = None,teamevent_id = None):
    dajax = Dajax()
    dajax.script("$(\'#dashboard #loading_dash_dajax\').hide();")
    if not request.user.is_authenticated():
        dajax.script('$.bootstrapGrowl("Login First",{type:"danger",delay:10000})')
        return dajax.json()
    if teamevent_id is None or shaastra_id is None:
        dajax.script('$.bootstrapGrowl("Invalid request",{type:"danger",delay:10000})')
        return dajax.json()
    try:
        teamevent = TeamEvent.objects.get(id = teamevent_id)
        print shaastra_id   
        user = UserProfile.objects.get(shaastra_id = shaastra_id).user
        if request.user not in teamevent.users.all():
            dajax.script('$.bootstrapGrowl("Invalid request: user not part of team",{type:"danger",delay:10000})')
            #Malicious attempt!?
            return dajax.json()
        if user in teamevent.users.all():
            dajax.script('$.bootstrapGrowl("Invalid request: User is already on the team, you cannot add again.",{type:"danger",delay:10000})')
            return dajax.json()
        #User cannot be added if on another team
        msg,team_name = has_team(user,teamevent.event_id)
        if msg == 'has_team':
            dajax.script('$.bootstrapGrowl("Invalid request: User is already on another team for this event. Multiple entries are prohibited.   ",{type:"danger",delay:10000})')
            return dajax.json()
        #The below statement will not be used, but, for malicious attempts to modify input params, we need it
        if user.username == request.user.username:
            dajax.script('$.bootstrapGrowl("Invalid request: You are already on the team.",{type:"danger",delay:10000})')
            return dajax.json()
        if teamevent.size() == teamevent.get_event().team_size_max:
            dajax.script('$.bootstrapGrowl("Sorry. Add member failed.You cannot have more than %s team members in your team.",{type:"danger",delay:10000})'% teamevent.get_event().team_size_min)
            return dajax.json()
        teamevent.users.add(user)
        teamevent.save()
        msg_update = 'Teammate %s was add to team %s for event %s on %s by %s'%(user.get_full_name(),teamevent.team_name,teamevent.get_event().title,str(timezone.now()),request.user.get_full_name())
        for user_team in teamevent.users.all():
            if not user_team.username == user.username:
                update = Update(tag = 'Team Edit',content = msg_update,user = user_team)
                update.save()
        msg_update_user = '******'%(teamevent.team_name,teamevent.get_event().title,str(timezone.now()),user.get_full_name())
        update = Update(tag = 'Team Add',content = msg_update_user,user = user)
        update.save()
        dajax.script('$.bootstrapGrowl("Addition success! %s has been added as a member of team %s",{type:"info",delay:10000,width:"auto"})'% (user.get_full_name(),teamevent.team_name))
        #TODO: Update create
        html_stuff = render_to_string('dashboard/welcome.html',{},RequestContext(request))
        if html_stuff:
            dajax.assign('#content_dash','innerHTML',html_stuff)
        return dajax.json()

    except:
        dajax.script('$.bootstrapGrowl("Invalid request. Check Shaastra ID entered",{type:"danger",delay:10000})')
        return dajax.json()
    return dajax.json()
Example #27
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()
Example #28
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()