Exemple #1
0
 def get(self):
     user = users.get_current_user()
     if user:
         render_to_response(self, 'index.html', {
             "user_name": user.nickname(),
         })
         # self.response.headers['Content-Type'] = 'text/html'
     else:
         self.redirect(users.create_login_url(self.request.uri))
Exemple #2
0
 def get(self):
     user = users.get_current_user()
     if user:
         render_to_response(self, 'index.html', {
             "user_name": user.nickname(),
         })
         # self.response.headers['Content-Type'] = 'text/html'
     else:
         self.redirect(users.create_login_url(self.request.uri))
Exemple #3
0
    def changelogin(self, request, template):
        cfg = GctConfig.objects.filter(id = 1)
        if not cfg:
            return HttpResponseRedirect('/gct/frontend/login/')
        elif not cfg[0].switch == '1':
            return HttpResponseRedirect('/gct/frontend/login/')
        if str(date.today()) >= cfg[0].off_date:            
            cfg[0].sys_open = '0'
            cfg[0].save()
        
        od = cfg[0].off_date
        nian = od[0:4]
        yue = od[5:7]
        ri = od[8:10]
        
        if request.method == "POST":
            lgn = request.POST.get('lgn',None)
            old_psw = request.POST.get('old_psw',None)
            psw = request.POST.get('psw', None)
            repsw = request.POST.get('repsw', None)
            se = self.DefaultModel.objects.filter(bmbh = lgn, password = old_psw)
            if not se:
                msg = {}
                msg["title"] = u"用户名或密码错误"
                msg["html"] = u"<p>您输入的用户名或原始密码错误,请核对后重新输入...</p>"
                msg["url"] = "/gct/frontend/changelogin/"
            
                gct = cfg[0]
                dicts = {'gct':gct, 'msg':msg,}                    
                return render_to_response(request, "gct/frontend/message.html", dicts,)

            if not psw == repsw:
                msg = {}
                msg["title"] = u"密码错误"
                msg["html"] = u"<p>两次所输入的密码不同,请重新输入...</p>"
                msg["url"] = "/gct/frontend/changelogin/" 

                gct = cfg[0]
                dicts = {'gct':gct, 'msg':msg, }
                return render_to_response(request, "gct/frontend/message.html", dicts,)
 
            else:
                se[0].password = psw
                se[0].save()

                msg = {}
                msg["title"] = u"密码修改成功"
                msg["html"] = u"<p>密码修改成功</p>"
                msg["url"] = "/gct/frontend/login/" 

                gct = cfg[0]
                dicts = {'gct':gct, 'msg':msg,}
                return render_to_response(request, "gct/frontend/message.html", dicts,)

        dicts = {'gct':cfg[0],'nian':nian,'yue':yue,'ri':ri,}     
        return render_to_response(request, "gct/frontend/changelogin.html", dicts,)
Exemple #4
0
    def apply(self, request, template):
        dicts = self._get_role(request)
        if not dicts.has_key('is_applicant'):
            return HttpResponseRedirect(self._get_login_url(request))

        if request.method == 'POST':
            name        = request.POST.get('name').strip()
            email       = request.POST.get('email').strip()
            content     = request.POST.get('content').strip()
            department  = HelpDeskUser.objects.filter(user = request.user, role='0')
            
            verified = True
            if not department:
                verified = False
            if name == None or name == '' or len(name) > 100:
                verified = False
            if email == None or email == '' or len(email) > 100:
                verified = False
            if content == '' or content == None:
                verified = False

            if verified == False:
                dicts = dicts.update({'name':name, 'email':email, 'content':content, 'verifyinfo':'请正确填写表单'})
                return render_to_response(request, template,dicts)

            department  = department[0]
            app         = self.ApplicationModel()
            app.uuid    = self._get_uuid()
            app.name    = name
            app.department = department.department
            app.email   = email
            app.submit_user = request.user
            app.content = content
            app.status  = 0
            if request.META.has_key('HTTP_X_FORWARDED_FOR'):
                app.ip = request.META['HTTP_X_FORWARDED_FOR']
            else:
                app.ip = request.META['REMOTE_ADDR']
            app.save()

             
            # 给管理员发通知邮件
            app.link = '/helpdesk/apply/allot?uuid=' + str(app.uuid)
            alloters = HelpDeskUser.objects.filter(role = '1')
            receiver = get_admin_email()
            send_mail(request,app, get_template('%smail_adm_apply.html' % self.template_dir), receiver, u'HelpDesk通知 【' + app.name +'】')
            
            # 给用户发通知邮件
            app.link = '/helpdesk/apply/query?uuid=' + str(app.uuid)
            send_mail(request,app, get_template('%smail_user_new.html'%self.template_dir), [app.email])
            
            return HttpResponseRedirect('/helpdesk/apply/result?uuid=' + str(app.uuid))

        return render_to_response(request,template,dicts)
Exemple #5
0
    def update(self, request, template, id):
        """
        实现单一对象的更新,该方法在子类中一般不需要重写
        """
        o = self._get_update_object(request, id)
        if o == None:
            return HttpResponseRedirect('/')

        update_dicts = self._get_update_dicts(request, o)
        update_dicts['o'] = o
        if update_dicts.has_key("form") and isinstance(update_dicts["form"],
                                                       ModelForm):
            update_dicts["form"] = self.DefaultForm(o, instance=o)

        if request.method == 'GET':
            if self.UseDjangoForm:
                f = self.DefaultForm(self.DefaultModel(), model_to_dict(o))
                update_dicts['form'] = str(f)
            return render_to_response(
                request,
                template,
                update_dicts,
            )

        if settings.DEBUG:
            print request.POST

        f = self.DefaultForm(o, request.POST)

        if not f.is_valid():
            update_dicts['form'] = str(f)
            return render_to_response(
                request,
                template,
                update_dicts,
            )
            #return HttpResponse('<table>'+str(f)+'</table>') if settings.DEBUG else HttpResponseBadRequest("bad request")

        #数据合格,更新记录
        f.save()
        self._after_update(request, o)

        next_url = request.POST.get('next_url', None)
        if next_url:
            next_url = re.sub('{pid}', str(o.pk), next_url)
            return HttpResponseRedirect(next_url)

        back_to_list = request.POST.get('back_to_list', None)
        if back_to_list:
            return HttpResponseRedirect('../../')

        return HttpResponseRedirect('../')
Exemple #6
0
def delete_message(request, email_address, msg_id):
    password = request.session.get(email_address + '-pass', '')
    view_dict = {}
    try:
        eu = EmailUser.get_obj(email_address)
        mb = eu.get_inbox(password)
        if mb.delete_message(msg_id):
            view_dict['content'] = 'Message Deleted Successfully!'
        else:
            view_dict['content'] = 'Message Does Not Exist!'
        return render_to_response(request, 'base.html', view_dict)
    except yaams.yaams_exceptions.PasswordProtected:
        view_dict['error_message'] = 'Password Required or Invalid Password Supplied!'
        return render_to_response(request, 'error.html', view_dict)
Exemple #7
0
    def score(self, request, template):
        cfg = GctConfig.objects.filter(id = 1)
        if not cfg:
            return HttpResponseRedirect('/gct/frontend/login/')
        elif not cfg[0].switch == '1':
            return HttpResponseRedirect('/gct/frontend/login/')
        if str(date.today()) >= cfg[0].off_date:            
            cfg[0].sys_open = '0'
            cfg[0].save()
                
        try:
            gct_bmbh = request.session['gct_bmbh']
            info = self.DefaultModel.objects.get(bmbh = gct_bmbh)
        except:
            msg = {}
            msg["title"] = u"尚未登录"
            msg["html"] = u"<p>您尚未登录,请登录后再进行相关操作...</p>"
            msg["url"] = "/gct/frontend/login/" 
                    
            gct = cfg[0]
            dicts = {'gct':gct, 'msg':msg,}
            return render_to_response(request, "gct/frontend/message.html", dicts,)
        
        if not info.activate_state == '1':
            msg = {}
            msg["title"] = u"尚未通过验证"
            msg["html"] = u"<p>您尚未通过验证,请您先进行信息验证...</p>"
            msg["url"] = "/gct/frontend/activate/" 
                    
            gct = cfg[0]
            dicts = {'gct':gct, 'msg':msg, 'info':info,}
            return render_to_response(request, "gct/frontend/message.html", dicts,)
        
        if not info.submit_state == '1':
            msg = {}
            msg["title"] = u"尚未确认提交复试科目"
            msg["html"] = u"<p>您尚未确认提交复试科目,请您先确认提交...</p>"
            msg["url"] = "/gct/frontend/textsubjects/" 
                    
            gct = cfg[0]
            dicts = {'gct':gct, 'msg':msg, 'info':info,}
            return render_to_response(request, "gct/frontend/message.html", dicts,)
        
        od = cfg[0].off_date
        nian = od[0:4]
        yue = od[5:7]
        ri = od[8:10]

        arg_dic = {'info':info,'gct':cfg[0],'nian':nian,'yue':yue,'ri':ri,}
        return render_to_response(request,template,arg_dic)
Exemple #8
0
    def add(self, request, template):
        """
           实现对象的新建,该方法在子类中一般不需要重写
        """
        o = self.DefaultModel()
        update_dicts = self._get_add_dicts(request)

        if request.method != 'POST':
            if self.UseDjangoForm:
                f = self.DefaultForm(o)
                update_dicts['form'] = str(f)

            return render_to_response(
                request,
                template,
                update_dicts,
            )

        if settings.DEBUG:
            print request.POST

        f = self.DefaultForm(o, request.POST)

        if not f.is_valid():
            if self.UseDjangoForm:
                update_dicts['form'] = str(f)
                return render_to_response(
                    request,
                    template,
                    update_dicts,
                )
            else:
                return HttpResponse(
                    '<table>' + str(f) +
                    '</table>') if settings.DEBUG else HttpResponseBadRequest(
                        "bad request")

        #数据合格,新增记录
        self._before_add(request)
        f.save()
        self._after_add(request, o)

        next_url = request.POST.get('next_url', None)
        print next_url
        if next_url:
            next_url = re.sub('{pid}', str(o.pk), next_url)
            return HttpResponseRedirect(next_url)

        #return HttpResponseRedirect('../'+str(o.pk)+'/')
        return HttpResponseRedirect("../")
Exemple #9
0
def login():
    # set mobilecookie to reduce is_mobile check-time
    response.set_cookie("mobile", str(is_mobile()))
    if not PYLOAD and SETUP:
        redirect("/setup")
    else:
        return render_to_response("login.html", proc=[pre_processor])
Exemple #10
0
def home(request, template="home.html"):
    u = request.user
#    mg = ModuleGroup.objects.get(pk=21)
#    mgs = g_filter_by_u(u, Module.objects.filter(module_group=mg).order_by('order_se'))

    #bg_gg
#    from missive.models import BgGgfl, BgGg

    main_dict = []
#    fls = BgGgfl.objects.filter(flbm__startswith = '0').order_by('flbm')
#    for fl in fls:
#        gg = BgGg.objects.filter(flbh=fl.flbm).order_by('-bh')[:5]
#        if gg:
#            main_dict.append([fl, gg])
    """*******************************************************************"""
#    fls = BgGgfl.objects.filter(flbm__startswith = '9')
#    s1_dict = BgGg.objects.filter(flbh__in=[fl.flbm for fl in fls]).order_by('-bh')[:5]
    """*******************************************************************"""

    dicts = {}
    perms = u.get_all_permissions()
    #dicts  ={'top_modules':get_modules(request,None)}
    top_modules = [ m for m in Module.objects.filter(upmodule__isnull = True, viewable = True).distinct().order_by('order_se') if not len(m.get_all_permissions() & perms) == 0]
    left = Module.objects.get(name="快捷操作")
    quick = [m for m in Module.objects.filter(upmodule = left) if not len(m.get_all_permissions() & perms) == 0]
    dicts['quick'] = quick
    dicts['top_modules'] = top_modules
    return render_to_response(request, template,dicts)
Exemple #11
0
def admin():
    # convert to dict
    user = dict([(name, toDict(y)) for name, y in PYLOAD.getAllUserData().iteritems()])
    perms = permlist()

    for data in user.itervalues():
        data["perms"] = {}
        get_permission(data["perms"], data["permission"])
        data["perms"]["admin"] = True if data["role"] is 0 else False


    s = request.environ.get('beaker.session')
    if request.environ.get('REQUEST_METHOD', "GET") == "POST":
        for name in user:
            if request.POST.get("%s|admin" % name, False):
                user[name]["role"] = 0
                user[name]["perms"]["admin"] = True
            elif name != s["name"]:
                user[name]["role"] = 1
                user[name]["perms"]["admin"] = False

            # set all perms to false
            for perm in perms:
                user[name]["perms"][perm] = False

            
            for perm in request.POST.getall("%s|perms" % name):
                user[name]["perms"][perm] = True

            user[name]["permission"] = set_permission(user[name]["perms"])

            PYLOAD.setUserPermission(name, user[name]["permission"], user[name]["role"])

    return render_to_response("admin.html", {"users": user, "permlist": perms}, [pre_processor])
Exemple #12
0
def person_view(request, handle):
    params = {
        'person': Person.objects.get(handle=handle)
        
    }
    
    return render_to_response(request, 'core/person_view.html', params)
Exemple #13
0
def downloads():
    root = PYLOAD.getConfigValue("general", "download_folder")

    if not isdir(root):
        return base([_("Download directory not found.")])
    data = {"folder": [], "files": []}

    items = listdir(fs_encode(root))

    for item in sorted([fs_decode(x) for x in items]):
        if isdir(safe_join(root, item)):
            folder = {"name": item, "path": item, "files": []}
            files = listdir(safe_join(root, item))
            for file in sorted([fs_decode(x) for x in files]):
                try:
                    if isfile(safe_join(root, item, file)):
                        folder["files"].append(file)
                except:
                    pass

            data["folder"].append(folder)
        elif isfile(join(root, item)):
            data["files"].append(item)

    return render_to_response("downloads.html", {"files": data}, [pre_processor])
Exemple #14
0
    def add(self, request, template):
        dicts = self._get_add_dicts(request)
        dicts.update(self._get_common_dicts(request))
        
        if request.method == 'POST':
            form = self.DefaultForm(request.POST)
            if form.is_valid():
                o = form.save()
                try:
                    o = form.save()
                except:
                    pass
                else:
                    o.save()
                    self._after_add(request, o)
                    next_url = request.GET.get('next_url')
                    if next_url:
                        return HttpResponseRedirect(next_url)
                    else:
                        path = request.path_info.strip('/').split('/')[:-1]
                        url = ''
                        for p in path:
                            url += '/' + p
                        return HttpResponseRedirect(url)
        else:
            form = self.DefaultForm()
            form.data = self._get_add_object(request)

        dicts['fields'] = self._get_fields(form)
        return render_to_response(request, template, dicts, )
Exemple #15
0
def apply(request):
    days = request.GET.get('days', 90)
    days = int(days)
    if not days or days < 5:
        days = 30
    nowDate = datetime.now()
    lastDate = nowDate - timedelta(days=days)
    dicts = get_role(request)
    app = Application.objects.filter(apply_time__gt=lastDate)
    applys = {}
    while lastDate <= nowDate:
        applys[lastDate.strftime('%Y-%m-%d')] = 0
        lastDate += timedelta(days=1)
    for a in app:
        t = a.apply_time.strftime('%Y-%m-%d')
        if applys.has_key(t):
            applys[t] += 1
        else:
            applys[t] = 1

    dicts['days'] = days
    applys = sorted(applys.iteritems(),
                    key=lambda applys: applys[0],
                    reverse=False)
    dicts['applys'] = simplejson.dumps(applys)
    return render_to_response(request, 'stats/apply.html', dicts)
Exemple #16
0
    def update(self, request, template, id):
        o = self._get_update_object(request, id)
        if o == None:
            return HttpResponseRedirect('/')

        dicts = self._get_update_dicts(request)
        dicts.update(self._get_common_dicts(request))
        # dicts['o'] = o
        # if update_dicts.has_key("form") and isinstance(update_dicts["form"],ModelForm):
        #     update_dicts["form"] = self.DefaultForm(o,instance=o)
        fields = []
        if request.method == 'POST':
            form = self.DefaultForm(request.POST, instance=o)
            if form.is_valid():
                for field in o._meta.fields:
                    if not field.primary_key:
                        setattr(o,field.name,form.cleaned_data[field.name])
                o.save()
                next_url = request.POST.get('next_url', None)
                if next_url:
                    return HttpResponseRedirect(next_url)
                return HttpResponseRedirect(dicts['list_url'])
        else:
            form = self.DefaultForm()
            form.data = o

        if type(form.data) == self.DefaultModel:
            form.data = form.data.__dict__
        dicts['fields'] = self._get_fields(form)

        return render_to_response(request, template, dicts,)
Exemple #17
0
    def update(self, request, template, id):
        o = self._get_update_object(request, id)
        if o == None:
            return HttpResponseRedirect('/')

        dicts = self._get_update_dicts(request)
        dicts.update(self._get_common_dicts(request))
        # dicts['o'] = o
        # if update_dicts.has_key("form") and isinstance(update_dicts["form"],ModelForm):
        #     update_dicts["form"] = self.DefaultForm(o,instance=o)
        fields = []
        if request.method == 'POST':
            form = self.DefaultForm(request.POST, instance=o)
            if form.is_valid():
                for field in o._meta.fields:
                    if not field.primary_key:
                        setattr(o, field.name, form.cleaned_data[field.name])
                o.save()
                next_url = request.POST.get('next_url', None)
                if next_url:
                    return HttpResponseRedirect(next_url)
                return HttpResponseRedirect(dicts['list_url'])
        else:
            form = self.DefaultForm()
            form.data = o

        if type(form.data) == self.DefaultModel:
            form.data = form.data.__dict__
        dicts['fields'] = self._get_fields(form)

        return render_to_response(
            request,
            template,
            dicts,
        )
Exemple #18
0
    def add(self, request, template):
        dicts = self._get_add_dicts(request)
        dicts.update(self._get_common_dicts(request))

        if request.method == 'POST':
            form = self.DefaultForm(request.POST)
            if form.is_valid():
                o = form.save()
                try:
                    o = form.save()
                except:
                    pass
                else:
                    o.save()
                    self._after_add(request, o)
                    next_url = request.GET.get('next_url')
                    if next_url:
                        return HttpResponseRedirect(next_url)
                    else:
                        path = request.path_info.strip('/').split('/')[:-1]
                        url = ''
                        for p in path:
                            url += '/' + p
                        return HttpResponseRedirect(url)
        else:
            form = self.DefaultForm()
            form.data = self._get_add_object(request)

        dicts['fields'] = self._get_fields(form)
        return render_to_response(
            request,
            template,
            dicts,
        )
Exemple #19
0
def task(request):
    days = request.GET.get('days', 90)
    days = int(days)
    if not days or days < 5:
        days = 30
    nowDate = datetime.now()
    lastDate = nowDate - timedelta(days=days)
    dicts = get_role(request)
    app = Application.objects.filter(apply_time__gt=lastDate)

    done = {}
    while lastDate <= nowDate:
        done[lastDate.strftime('%Y-%m-%d')] = 0
        lastDate += timedelta(days=1)
    for a in app:
        if a.finish_time:
            f = a.finish_time.strftime('%Y-%m-%d')
            if done.has_key(f):
                done[f] += 1
            else:
                done[f] = 1
    dicts['days'] = days
    done = sorted(done.iteritems(), key=lambda done: done[0], reverse=False)
    dicts['done'] = simplejson.dumps(done)

    return render_to_response(request, 'stats/task.html', dicts)
Exemple #20
0
def downloads():
    root = PYLOAD.getConfigValue("general", "download_folder")

    if not isdir(root):
        return base([_('Download directory not found.')])
    data = {'folder': [], 'files': []}

    items = listdir(fs_encode(root))

    for item in sorted([fs_decode(x) for x in items]):
        if isdir(save_join(root, item)):
            folder = {'name': item, 'path': item, 'files': []}
            files = listdir(save_join(root, item))
            for file in sorted([fs_decode(x) for x in files]):
                try:
                    if isfile(save_join(root, item, file)):
                        folder['files'].append(file)
                except:
                    pass

            data['folder'].append(folder)
        elif isfile(join(root, item)):
            data['files'].append(item)

    return render_to_response('downloads.html', {'files': data},
                              [pre_processor])
Exemple #21
0
    def add(self, request, template):
        """
           实现对象的新建,该方法在子类中一般不需要重写
        """ 
        o = self.DefaultModel()

        update_dicts = self._get_update_dicts(request)
        if request.method != 'POST':
            return render_to_response(request, template, update_dicts, )

        if settings.DEBUG:
            print 111,request.POST, request.REQUEST, request.FILES

        f = self.DefaultForm(o, request.POST, request.FILES)

        if not f.is_valid():
            return HttpResponse('<table>'+str(f)+'</table>') if settings.DEBUG else HttpResponseBadRequest("bad request")

        #数据合格,新增记录
        self._before_add(request)
        f.save()
        self._after_add(request, o)

        next_url = request.POST.get('next_url', None)
        if next_url:
            next_url = re.sub('{pid}', str(o.id), next_url)
            return HttpResponseRedirect(next_url)

        return HttpResponseRedirect('../'+str(o.id)+'/')
Exemple #22
0
def downloads():
    root = PYLOAD.getConfigValue("general", "download_folder")

    if not isdir(root):
        return base([_('Download directory not found.')])
    data = {
        'folder': [],
        'files': []
    }

    items = listdir(fs_encode(root))

    for item in sorted([fs_decode(x) for x in items]):
        if isdir(save_join(root, item)):
            folder = {
                'name': item,
                'path': item,
                'files': []
            }
            files = listdir(save_join(root, item))
            for file in sorted([fs_decode(x) for x in files]):
                try:
                    if isfile(save_join(root, item, file)):
                        folder['files'].append(file)
                except:
                    pass

            data['folder'].append(folder)
        elif isfile(join(root, item)):
            data['files'].append(item)

    return render_to_response('downloads.html', {'files': data}, [pre_processor])
Exemple #23
0
def admin():
    # convert to dict
    user = dict([(name, toDict(y)) for name, y in PYLOAD.getAllUserData().iteritems()])
    perms = permlist()

    for data in user.itervalues():
        data["perms"] = {}
        get_permission(data["perms"], data["permission"])
        data["perms"]["admin"] = True if data["role"] is 0 else False


    s = request.environ.get('beaker.session')
    if request.environ.get('REQUEST_METHOD', "GET") == "POST":
        for name in user:
            if request.POST.get("%s|admin" % name, False):
                user[name]["role"] = 0
                user[name]["perms"]["admin"] = True
            elif name != s["name"]:
                user[name]["role"] = 1
                user[name]["perms"]["admin"] = False

            # set all perms to false
            for perm in perms:
                user[name]["perms"][perm] = False

            
            for perm in request.POST.getall("%s|perms" % name):
                user[name]["perms"][perm] = True

            user[name]["permission"] = set_permission(user[name]["perms"])

            PYLOAD.setUserPermission(name, user[name]["permission"], user[name]["role"])

    return render_to_response("admin.html", {"users": user, "permlist": perms}, [pre_processor])
Exemple #24
0
    def evaluate(self, request, template):
        try:
            if request.method == 'GET':
                uuid = request.GET.get('uuid')
                score = request.GET.get('e')
                app = self.ApplicationModel.objects.get(uuid=uuid)
                dicts = {}
                dicts['app'] = app
                dicts['e'] = score
                es = dict(self.ApplicationModel.evaluate_choices)
                dicts['ename'] = es[score]
                dicts['uuid'] = uuid
                score = int(score)
                if score < 60:
                    return render_to_response(request, 'evaluate.html', dicts)
                app.evaluation = str(score)
                app.evaluate_time = datetime.now()
                app.save()
            elif request.method == 'POST':
                uuid = request.POST.get('uuid')
                score = request.POST.get('e')
                app = self.ApplicationModel.objects.get(uuid=uuid)
                content = request.POST.get('content')
                if content == '' or content == None:
                    return HttpResponse('提交失败')
                app.evaluate_content = content
                app.evaluation = str(score)
                app.evaluate_time = datetime.now()
                app.save()
            return HttpResponse('提交成功,谢谢。')

        except:
            return HttpResponse('提交失败,请稍后再试。。。')
Exemple #25
0
    def history(self, request, template):
        '''用户申请历史记录'''
        dicts = self._get_role(request)
        if not dicts.has_key('is_applicant'):
            return HttpResponseRedirect(self._get_login_url(request))

        name = request.GET.get('name')
        email = request.GET.get('email')
        status = request.GET.get('status')
        page = request.GET.get('page')
        user = HelpDeskUser.objects.filter(user=request.user, role='0')
        user = user[0].user
        # dep     = [u.department for u in user]
        # apps    = self.ApplicationModel.objects.filter(department__in = dep).order_by('-apply_time')

        # only login user
        apps = self.ApplicationModel.objects.filter(
            submit_user=user).order_by('-apply_time')

        if name:
            apps = apps.filter(name__contains=name)
        if email:
            apps = apps.filter(email__contains=email)
        if status:
            apps = apps.filter(status=status)

        p = get_page(apps, request)

        dicts['p'] = p
        dicts['statuslist'] = dict(self.ApplicationModel.status_choices)
        return render_to_response(request, get_template(template), dicts)
Exemple #26
0
def login(request, template='auth/userlogin.html', redirect_field_name=REDIRECT_FIELD_NAME):
    if request.GET.has_key('admin'):
        template = 'auth/adminlogin.html'

    if request.method == 'POST':
        redirect_to = request.REQUEST.get(redirect_field_name, '')
        loginname = request.POST.get('loginname', None)
        password = request.POST.get('password', None)

        user = authenticate(loginname = loginname, password = password)

        if user:

#            if user.is_alias():
#                __user = user
#                user = __user.alias_user
#                user.backend = __user.backend

            from auth import login
            login(request, user)

            if not redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL

            if request.is_ajax():
                return render_to_response_json({"location": redirect_to, "errcode":0})

            return HttpResponseRedirect(redirect_to)

        if request.is_ajax():
            return render_to_response_json({"errcode":101})

    redirect_to =  request.META.get('HTTP_REFERER', "")
    return render_to_response(request, template, {redirect_field_name: redirect_to})
Exemple #27
0
 def evaluate(self, request, template):
     try:
         if request.method == 'GET': 
             uuid = request.GET.get('uuid')
             score = request.GET.get('e')
             app = self.ApplicationModel.objects.get(uuid = uuid)   
             dicts = {}
             dicts['app'] = app
             dicts['e'] = score
             es = dict(self.ApplicationModel.evaluate_choices)
             dicts['ename'] =es[score]
             dicts['uuid'] = uuid
             score = int(score)
             if score < 60:
                 return render_to_response(request, 'evaluate.html', dicts)
             app.evaluation = str(score)
             app.evaluate_time = datetime.now()
             app.save()
         elif request.method == 'POST':
             uuid = request.POST.get('uuid')
             score = request.POST.get('e')
             app = self.ApplicationModel.objects.get(uuid = uuid) 
             content = request.POST.get('content')
             if content == '' or content == None:
                 return HttpResponse('提交失败')
             app.evaluate_content = content
             app.evaluation = str(score)
             app.evaluate_time = datetime.now()
             app.save()
         return HttpResponse('提交成功,谢谢。')
    
     except:
         return HttpResponse('提交失败,请稍后再试。。。')
Exemple #28
0
    def history(self, request, template):
        '''用户申请历史记录'''
        dicts = self._get_role(request)
        if not dicts.has_key('is_applicant'): 
            return HttpResponseRedirect(self._get_login_url(request))

        name    = request.GET.get('name')
        email   = request.GET.get('email')
        status  = request.GET.get('status')
        page    = request.GET.get('page')
        user    = HelpDeskUser.objects.filter(user = request.user, role='0')
        user    = user[0].user
        # dep     = [u.department for u in user]
        # apps    = self.ApplicationModel.objects.filter(department__in = dep).order_by('-apply_time')

        # only login user 
        apps = self.ApplicationModel.objects.filter(submit_user = user).order_by('-apply_time')

        if name:
            apps = apps.filter(name__contains = name)
        if email:
            apps = apps.filter(email__contains = email)
        if status:
            apps = apps.filter(status = status)

        p = get_page(apps, request)
        
        dicts['p'] = p
        dicts['statuslist'] = dict(self.ApplicationModel.status_choices)
        return render_to_response(request, get_template(template), dicts)
Exemple #29
0
def login():
    # set mobilecookie to reduce is_mobile check-time
    response.set_cookie("mobile", str(is_mobile()))
    if not PYLOAD and SETUP:
        redirect("/setup")
    else:
        return render_to_response("login.html", proc=[pre_processor])
Exemple #30
0
def task(request):
    days = request.GET.get('days', 90)
    days = int(days)
    if not days or days < 5:
        days = 30
    nowDate = datetime.now()
    lastDate = nowDate - timedelta(days=days)
    dicts = get_role(request)
    app = Application.objects.filter(apply_time__gt =lastDate)

    done = {}
    while lastDate <= nowDate:
        done[lastDate.strftime('%Y-%m-%d')] = 0
        lastDate += timedelta(days=1)
    for a in app:
        if a.finish_time:
            f = a.finish_time.strftime('%Y-%m-%d')
            if done.has_key(f):
                done[f] += 1
            else:
                done[f] = 1
    dicts['days'] = days
    done = sorted(done.iteritems(), key=lambda done:done[0], reverse=False)
    dicts['done'] = simplejson.dumps(done)

    return render_to_response(request,'stats/task.html', dicts)
Exemple #31
0
    def list(self, request, template):
        """
            在原来的基础上添加了文件上传和xls导入,添加了分页后数据处理的接口
        """
        u = request.user
        ls = self._get_list(request)
       
        #重写_get_list的时候返回的ls 如果是None会报错,强制转换一下增加可用性
        if ls == None:
            ls = self.DefaultModel.objects.none()

        args = {}
        for ak in self.list_args.keys():
            if re.search('_doption$', ak):
                if request.GET.get(ak , None):
                    datestr = (request.GET.get(ak, None)).split('-')
                    args[str(self.list_args.get(ak))] = datetime.strptime((''.join((datestr[0],'-',datestr[1],'-01'))), '%Y-%m-%d')
            elif re.search('_option$', self.list_args.get(ak)):
                if request.GET.get(ak, None) and request.GET.get(ak + '_option', None):
                    args[str(ak+'__'+request.GET.get(ak + '_option', None))] = str(request.GET.get(ak, None))
#            elif re.search('_extra$', self.list_args.get(ak)):
#                if request.GET.get(ak, None):
#                    ls = self._extra_filter(request, ls, ak,self.list_args[ak])
            else:
                if request.GET.get(ak, None):
                    try:
                        args[str(self.list_args.get(ak))] = str(request.GET.get(ak, None))
                    except UnicodeEncodeError:
                        args[str(self.list_args.get(ak))] = request.GET.get(ak, None)
                
        ls = ls.filter(**args)
        ls = self._extra_filter(request,ls)
        
        
        if(request.GET.get('excel')):
            if request.method == "POST":
                cols = request.POST.getlist("cols")
                return self.csv_export(request, ls, cols)
            
        try:
            p = get_page(ls, request)
        except EmptyPage:
            return HttpResponseRedirect('./')

        c_list = []
        if self.csv_columns:
            for c in self.csv_columns:
                c_list.append(c[0].decode("utf-8"));
                
        p = self._deal_page_data(request,p)
        list_dicts = {'p':p, 'excel_cs':c_list}
        list_dicts.update(self._get_list_dicts(request))
        
        if(request.GET.get('upload')):
            if request.method == "POST":
                return self.upload(request, template, list_dicts)
            
        
        return render_to_response(request, template, list_dicts )   
Exemple #32
0
def login_post():
    username = request.forms.get("username")
    password = request.forms.get("password")
    user = PYLOAD.checkAuth(username, password)
    if not user:
        return render_to_response("login.html", {"errors": True}, [pre_processor])
    set_session(request, user)
    return redirect("/")
Exemple #33
0
def login_url(request, loginname, ts, authcode, template = "auth/redirect.html"):
    user = authenticate(loginname = loginname, ts = ts, authcode = authcode)
    if user:
        from auth import login
        login(request, user)
        redirect = request.REQUEST.get(REDIRECT_FIELD_NAME, "")
        return render_to_response(request, template, {REDIRECT_FIELD_NAME: redirect})
    return HttpResponseForbidden
Exemple #34
0
    def result(self, request, template):
        dicts = self._get_role(request)
        if not dicts.has_key('is_applicant'):
            return HttpResponseRedirect(self._get_login_url(request))

        uuid = request.GET.get('uuid')
        dicts['uuid'] = uuid
        return render_to_response(request, get_template(template), dicts)
Exemple #35
0
    def result(self, request, template):
        dicts = self._get_role(request)
        if not dicts.has_key('is_applicant'):
            return HttpResponseRedirect(self._get_login_url(request))

        uuid = request.GET.get('uuid')
        dicts['uuid'] = uuid
        return render_to_response(request, get_template(template), dicts)
Exemple #36
0
def user_login(request):
	
	if request.method == 'GET':
		uform = UserLoginForm()
		return render_to_response(request, 'user/login.html', {'uform':uform})
		
	elif request.method == 'POST':
		
		uform = UserLoginForm(request.POST)
		if uform.is_valid():
			cd = uform.cleaned_data
			user = authenticate(username=cd['username'], password=cd['password'])
			if user and user.is_authenticated():
				login(request, user)
				return HttpResponseRedirect(reverse('sodo.index'))
		
		return render_to_response(request, 'user/login.html', {'uform':uform})
Exemple #37
0
def login_post():
    username = request.forms.get("username")
    password = request.forms.get("password")
    user = PYLOAD.checkAuth(username, password)
    if not user:
        return render_to_response("login.html", {"errors": True}, [pre_processor])
    set_session(request, user)
    return redirect("/")
Exemple #38
0
def user_profile(request, username):

	if request.method == 'GET':
		# Retrieve user
		profileuser = User.objects.get(username__exact=username)
		
		uform = UserProfileForm(instance=profileuser);
		
		return render_to_response(request, 'user/user.html', {'profileuser':profileuser, 'uform':uform})

	elif request.method == 'POST':
		
		profileuser = User.objects.get(username__exact=username) # Retrieve the specified user
		uform = UserProfileForm(request.POST, instance=profileuser) # Populate the UserProfileForm with the input data from client side				

		if uform.is_valid():

			user = uform.save()									
			cd = uform.cleaned_data
			
#			# Process the data in form.cleaned_data
#			media = None
#			try:
#				media = Media()
#				tmp_img = db.Blob(request.FILES['profile_image'].read())
#				media.name = request.FILES['profile_image'].name
#				media.is_blob = True
#				media.blob_content = tmp_img
#				media.content_type = request.FILES['profile_image'].content_type
#				media.put()
#			except KeyError:
#				media = None
#
#			if media:
#				user.profile_image = media
#				user.put()
	
			
			message = {'text': _("Profile updated"), 'type':'success'}
		else:
			#uform = UserProfileForm(instance=user)
			message = {'text':_("Profile update failed"), 'type':'error'}		
			return render_to_response(request, 'user/user.html', {'uform':uform, 'profileuser':profileuser, 'message':message, 'errors':uform.errors })

		return render_to_response(request, 'user/user.html', {'uform':uform, 'profileuser':profileuser, 'message':message})
Exemple #39
0
def check_inbox(request, email):
	try:
                eu = EmailUser.get_obj(email)
                if not eu:
                    return render_to_response(request, 'error.html', {'error_message' : 'Uh Oh!!!!! eu is None!!!?'})
                if not request.session.get(email + '-auth', False):
                    mb = eu.get_inbox()
                    if not mb:
                        return render_to_response(request,'error.html', {'error_message' : 'Uh - oh Mb is None?!'})
                else:
                    password = request.session.get(email + '-pass', None)
                    mb = eu.get_inbox(password)
                output_dict = { 'messages' : mb.get_latest_messages(mb.get_message_count()), 'email' : email}
                return render_to_response(request, 'listing.html', output_dict)
	except yaams.yaams_exceptions.NoSuchUser:
		return render_to_response(request, 'error.html', {'error_message' : 'Email Address Not Found!'})
        except yaams.yaams_exceptions.PasswordProtected:
            password = request.POST.get('password', None)
            if not password:
                return render_to_response(request, 'password_protected.html', {})
            else:
                if eu.check_password(password):
                    request.session[email + '-auth'] = True
                    request.session[email + '-pass'] = password
                    mb = eu.get_inbox(password)
                    output_dict = { 'messages' : mb.get_latest_messages(mb.get_message_count()), 'email' : email}
                    return render_to_response(request, 'listing.html', output_dict)
                else:
                    return render_to_response(request, 'error.html', { 'error_message' : 'Invalid Password!' })
Exemple #40
0
def serve_template(path):
    """ Serve backbone templates """
    args = path.split("/")
    args.insert(1, "backbone")
    try:
        return render_to_response("/".join(args))
    except TemplateNotFound, e:
        print e
        return HTTPError(404, "Not Found")
Exemple #41
0
def collector():
    queue = PYLOAD.getCollector()

    queue.sort(key=attrgetter("order"))

    return render_to_response('queue.html', {
        'content': queue,
        'target': 0
    }, [pre_processor])
Exemple #42
0
def home(request):
    dicts = {}
    dicts['appointments'] = get_appointments(request)
    dicts['oncedisable'] = OnceDisablePeriod.objects.all()
    dicts['dailydisable'] = DailyDisablePeriod.objects.all()
    dicts['weeklydisable'] = WeeklyDisablePeriod.objects.all()
    dicts['hourrange'] = HourRange.objects.all()[0]
    dicts['weekdayrange'] = WeekdayRange.objects.all()[0]
    return render_to_response(request, 'home.html', dicts)
Exemple #43
0
def check_message(request, email, msg_id):
	try:
                password = request.session.get(email + '-pass', '')
                msg_dict = { 'msg_user_exists' : True, 'email_address' : email, 'msg_id' : msg_id }
                eu = EmailUser.get_obj(email)
		mb = eu.get_inbox(password)
		msg = mb.get_message(msg_id)
                msg_dict['message'] = msg
                msg_dict['source_address'] = email
                output = render_to_response(request, 'view_message.html', msg_dict)
	except (yaams.yaams_exceptions.NoSuchUser, yaams.yaams_exceptions.NoSuchMessage):
                msg_dict['msg_user_exists'] = False
		output = render_to_response(request, 'view_message.html', msg_dict)
        except yaams.yaams_exceptions.PasswordProtected:
                return render_to_response(request, 'error.html', {'error_message' : 'Email requires password!<br /> Please enter a valid password to access this email.'})
	except Exception as i:
		output = "Unexpected error!<br />%s" % i
	return HttpResponse(output)
Exemple #44
0
def serve_template(path):
    """ Serve backbone templates """
    args = path.split("/")
    args.insert(1, "backbone")
    try:
        return render_to_response("/".join(args))
    except TemplateNotFound, e:
        print e
        return HTTPError(404, "Not Found")
Exemple #45
0
 def pay_fail(self, request, template):
     cfg = GctConfig.objects.filter(id = 1)
     if not cfg:
         return HttpResponseRedirect('/gct/frontend/login/')
     
     try:
         gct_bmbh = request.session['gct_bmbh']
         info = self.DefaultModel.objects.get(bmbh = gct_bmbh)
     except:
         msg = {}
         msg["title"] = u"尚未登录"
         msg["html"] = u"<p>您尚未登录,请登录后再进行相关操作...</p>"
         msg["url"] = "/gct/frontend/login/" 
                 
         gct = cfg[0]
         dicts = {'gct':gct, 'msg':msg,}
         return render_to_response(request, "gct/frontend/message.html", dicts,)
     return render_to_response(request, template,)
Exemple #46
0
def send_message(request):
    """NOTE THAT I KNOW THIS DOESN'T SECURE THE SOURCE ADDRESS! THIS IS ANONYMOUS MAIL!"""
    source_address = request.POST.get('source_address', '')
    subject = request.POST.get('subject', '')
    target_address = request.POST.get('target_address', '')
    
    if request.POST.get('body', False):
        send_email(settings.SMTP_SETTINGS, source_address, target_address, subject, request.POST.get('body'))
        return render_to_response(request, 'base.html', { 'content' : 'Message Sent!'})
    else:
        view_dict = {
        
        'source_address' : source_address,
        'target_address' : target_address,
        'subject' : subject
        
        }
        return render_to_response(request, 'send_form.html', view_dict)
Exemple #47
0
def home(request):
    dicts = {}
    dicts['appointments'] = get_appointments(request)
    dicts['oncedisable'] = OnceDisablePeriod.objects.all()
    dicts['dailydisable'] = DailyDisablePeriod.objects.all()
    dicts['weeklydisable'] = WeeklyDisablePeriod.objects.all()
    dicts['hourrange'] = HourRange.objects.all()[0]
    dicts['weekdayrange'] = WeekdayRange.objects.all()[0]
    return render_to_response(request, 'home.html', dicts)
Exemple #48
0
 def get(self):
     user = users.get_current_user()
     final_status = True
     services = []
     for machine_key, machine_value in MACHINES.items():
         machine_services = machine_value["services"]
         for service in machine_services:
             address = service["address"]
             status_code = 500
             try:
                 status_code = urlfetch.fetch(address).status_code
             except:
                 status_code = -1
             final_status = final_status and status_code == 200
             service["status"] = status_code
             services.append(service)
     render_to_response(self, 'index.html', {
         "services": services,
         "final_status": final_status,
     })
Exemple #49
0
def edit(request, pg='/'):
    try:
        page = Page.objects.get(pg=pg)
    except:  # we still have to pass 'pg' to the template...
        page = {'pg': pg}

    template = 'wiki/edit.html'
    context = {
        'page': page,
    }
    return render_to_response(request, template, context)
Exemple #50
0
def login_post():
    user = request.forms.get("username")
    password = request.forms.get("password")

    info = PYLOAD.checkAuth(user, password)

    if not info:
        return render_to_response("login.html", {"errors": True}, [pre_processor])

    set_session(request, info)
    return relative_redirect("home")
Exemple #51
0
 def query(self, request, template):
     """
     实现对象的查询页面显示,该方法在子类中一般不需要重写
     """
     if request.method == 'POST':
         """处理下url,免得字段太多,url太长,不美。Contract里面已经用起来了,其他模块可以用"""
         redirect_url = "../?"
         for p in request.POST:
             if request.POST[p]:
                 redirect_url += "&" + p + "=" + request.POST[p]
         return HttpResponseRedirect(redirect_url)
     return render_to_response(request, template,
                               self._get_update_dicts(request))
Exemple #52
0
def home():
    try:
        res = [toDict(x) for x in PYLOAD.statusDownloads()]
    except:
        s = request.environ.get('beaker.session')
        s.delete()
        return relative_redirect("login")

    for link in res:
        if link["status"] == 12:
            link["information"] = "%s kB @ %s kB/s" % (link["size"] - link["bleft"], link["speed"])

    return render_to_response("home.html", {"res": res}, [pre_processor])
Exemple #53
0
def config():
    conf = PYLOAD.getConfig()
    plugin = PYLOAD.getPluginConfig()

    conf_menu = []
    plugin_menu = []

    for entry in sorted(conf.keys()):
        conf_menu.append((entry, conf[entry].description))

    for entry in sorted(plugin.keys()):
        plugin_menu.append((entry, plugin[entry].description))

    accs = PYLOAD.getAccounts(False)

    for data in accs:
        if data.trafficleft == -1:
            data.trafficleft = _("unlimited")
        elif not data.trafficleft:
            data.trafficleft = _("not available")
        else:
            data.trafficleft = formatSize(data.trafficleft * 1024)

        if data.validuntil == -1:
            data.validuntil = _("unlimited")
        elif not data.validuntil:
            data.validuntil = _("not available")
        else:
            t = time.localtime(data.validuntil)
            data.validuntil = time.strftime("%d.%m.%Y", t)

        if "time" in data.options:
            try:
                data.options["time"] = data.options["time"][0]
            except:
                data.options["time"] = "0:00-0:00"

        if "limitDL" in data.options:
            data.options["limitdl"] = data.options["limitDL"][0]
        else:
            data.options["limitdl"] = "0"

    return render_to_response(
        'settings.html', {
            'conf': {
                'plugin': plugin_menu,
                'general': conf_menu,
                'accs': accs
            },
            'types': PYLOAD.getAccountTypes()
        }, [pre_processor])
Exemple #54
0
def evaluate(request):
    dicts = get_role(request)
    app = Application.objects.filter(evaluation__isnull=False)
    total = app.count()
    eva = {}
    eva_list = []
    for e in Application.evaluate_choices:
        eva_list.append([int(e[0]), e[1]])
        eva[int(
            e[0])] = app.filter(evaluation=e[0]).count() * 1.0 / total * 100
    eva = sorted(eva.iteritems(), key=lambda eva: eva[0], reverse=True)
    dicts['evaluation'] = simplejson.dumps(eva)
    dicts['eva_list'] = simplejson.dumps(eva_list)
    return render_to_response(request, 'stats/evaluate.html', dicts)
Exemple #55
0
def atype(request):
    type_list = []
    count = []
    types = dict(ApplyType.type_choices)
    index = 0
    for t in types:
        type_list.append([index, types[t]])
        count.append([index, ApplyType.objects.filter(type=t).count()])
        index += 20
    dicts = get_role(request)
    dicts['count'] = simplejson.dumps(count)

    dicts['type_list'] = simplejson.dumps(type_list)

    return render_to_response(request, 'stats/type.html', dicts)
Exemple #56
0
def show(request, pg='/'):
    try:
        page = Page.objects.get(pg=pg)
        page.update()
        template = 'wiki/show.html'
    except:
        if request.user.is_authenticated:
            return redirect('wiki_edit', pg)
        else:
            template = 'wiki/404.html'

    context = {
        'page': page,
    }
    return render_to_response(request, template, context)
Exemple #57
0
def load_config(category, section):
    conf = None
    if category == "general":
        conf = PYLOAD.getConfigDict()
    elif category == "plugin":
        conf = PYLOAD.getPluginConfigDict()

    for key, option in conf[section].iteritems():
        if key in ("desc","outline"): continue

        if ";" in option["type"]:
            option["list"] = option["type"].split(";")

        option["value"] = decode(option["value"])

    return render_to_response("settings_item.html", {"skey": section, "section": conf[section]})
Exemple #58
0
def info():
    conf = PYLOAD.getConfigDict()

    if hasattr(os, "uname"):
        extra = os.uname()
    else:
        extra = tuple()

    data = {"python": sys.version,
            "os": " ".join((os.name, sys.platform) + extra),
            "version": PYLOAD.getServerVersion(),
            "folder": abspath(PYLOAD_DIR), "config": abspath(""),
            "download": abspath(conf["general"]["download_folder"]["value"]),
            "freespace": formatSize(PYLOAD.freeSpace()),
            "remote": conf["remote"]["port"]["value"],
            "webif": conf["webinterface"]["port"]["value"],
            "language": conf["general"]["language"]["value"]}

    return render_to_response("info.html", data, [pre_processor])
Exemple #59
0
def passwd(request):
    dicts = get_role(request)
    if request.method == 'POST':
        old_passwd = request.POST.get('old_passwd')
        passwd = request.POST.get('passwd')
        passwd_check = request.POST.get('passwd_check')
        if not old_passwd or not passwd or not passwd_check:
            dicts['msg'] = '请完整填写表单!'
        elif not request.user.check_password(old_passwd):
            dicts['msg'] = '当前密码错误!'
        elif passwd != passwd_check:
            dicts['msg'] = '两次输入的新密码不一致!'
        else:
            try:
                request.user.set_password(passwd)
                request.user.save()
                dicts['msg'] = "密码修改成功!"
            except:
                dicts['msg'] = "密码修改失败!"
    return render_to_response(request, 'passwd.html', dicts)
Exemple #60
0
    def query(self, request, template):
        '''用户申请记录查询'''
        dicts = self._get_role(request)
        if not dicts.has_key('is_applicant'):
            return HttpResponseRedirect(self._get_login_url(request))

        uuid = request.GET.get('uuid')
        if uuid:
            try:
                appobj = self.ApplicationModel.objects.get(pk=uuid)
                obj = False
                for application in dicts['apply_categories']:
                    if application['model'].__name__ == appobj.category:
                        obj = application['model'].objects.get(uuid=uuid)
                        dicts['application'] = appobj.category
                        dicts['apply_info_template'] = application[
                            'short_tag'] + '/info.html'
                        break

                for application in dicts['apply_categories']:
                    try:
                        obj = application['model'].objects.get(uuid=uuid)
                    except:
                        obj = None
                    if obj:
                        dicts['application'] = application['tag']
                        dicts['apply_info_template'] = application[
                            'short_tag'] + '/info.html'
                        appobj.category = application['tag']
                        appobj.save()
                        break
            except:
                obj = False

            dicts['uuid'] = uuid
            if not obj:
                dicts['result'] = 'UUID 有误'
            else:
                dicts['app'] = obj
                dicts['task'] = appobj.task_set.filter()
        return render_to_response(request, get_template(template), dicts)