Esempio n. 1
0
def attachment(request, object_id, update_id=None):
    dajax = Dajax()

    try:

        if object_id:
            attachments = Attachment.objects.filter(attached_object__id=object_id)
            template = 'core/tags/attachments_block'

            object_markup = render_to_string(template,
                               {'object_id': object_id, 'attachments': attachments},
                               context_instance=RequestContext(request),
                               response_format='html')

            dajax.add_data({'target': 'div.attachment-block[object="%s"]'%object_id, 'content': object_markup}, 'treeio.add_data')

        if update_id:
            attachments = Attachment.objects.filter(attached_record__id=update_id)
            template = 'core/tags/attachments_record_block'
            update_markup = render_to_string(template,
                               {'update_id': update_id, 'attachments': attachments},
                               context_instance=RequestContext(request),
                               response_format='html')
            dajax.add_data({'target': 'div.attachment-record-block[object="%s"]'%update_id, 'content': update_markup}, 'treeio.add_data')

    except Exception, e:
        print e
Esempio n. 2
0
def tags(request, target, object_id, edit=False, formdata={}):
    dajax = Dajax()
    
    response_format = 'html'
    object = Object.objects.get(pk=object_id)
    
    tags = object.tags.all()
    form = None
    if 'tags' in formdata and not type(formdata['tags']) == list:
        formdata['tags'] = [formdata['tags']]
    
    if edit or formdata:
        if formdata.get('tags_object', 0) == unicode(object.id):
            form = TagsForm(tags, formdata)
            if form.is_valid():
                if 'multicomplete_tags' in formdata:
                    tag_names = formdata.get('multicomplete_tags').split(',')
                    new_tags = []
                    for name in tag_names:
                        name = name.strip()
                        if name:
                            try:
                                tag = Tag.objects.get(name=name)
                            except Tag.DoesNotExist:
                                tag = Tag(name=name)
                                tag.save()
                            new_tags.append(tag)
                else:
                    new_tags = form.is_valid()
                    
                object.tags.clear()
                for tag in new_tags:
                    object.tags.add(tag)
                tags = object.tags.all()
                form = None
        else:
            form = TagsForm(tags)
    
    context = {'object': object,
               'tags': tags,
               'form': form }    
    
    context = converter.preprocess_context(context)
    
    output = render_to_string('core/ajax/tags_box', context,
                               context_instance=RequestContext(request),
                               response_format=response_format)
    
    dajax.add_data({'target': target, 'content': output}, 'treeio.add_data')
    return dajax.json()
Esempio n. 3
0
def get_more(request, target='#more-news', skip=20):
    dajax = Dajax()
    
    profile = request.user.get_profile()
    query = _get_filter_query(profile) & (~Q(author=profile) | Q(record_type='share') | Q(score__gt=0)) 
    updates = UpdateRecord.objects.filter(query).distinct()[skip:skip+20]
    
    output = render_to_string('news/ajax/index',
                               {'updates': updates, 'skip': skip+20},
                               context_instance=RequestContext(request),
                               response_format='html')
    
    dajax.add_data({'target': target, 'content': output}, 'maker.add_data')
    return dajax.json()
Esempio n. 4
0
File: ajax.py Progetto: vovkd/treeio
def tags(request, target, object_id, edit=False, formdata={}):
    dajax = Dajax()

    response_format = 'html'
    object = Object.objects.get(pk=object_id)

    tags = object.tags.all()
    form = None
    if 'tags' in formdata and not type(formdata['tags']) == list:
        formdata['tags'] = [formdata['tags']]

    if edit or formdata:
        if formdata.get('tags_object', 0) == unicode(object.id):
            form = TagsForm(tags, formdata)
            if form.is_valid():
                if 'multicomplete_tags' in formdata:
                    tag_names = formdata.get('multicomplete_tags').split(',')
                    new_tags = []
                    for name in tag_names:
                        name = name.strip()
                        if name:
                            try:
                                tag = Tag.objects.get(name=name)
                            except Tag.DoesNotExist:
                                tag = Tag(name=name)
                                tag.save()
                            new_tags.append(tag)
                else:
                    new_tags = form.is_valid()

                object.tags.clear()
                for tag in new_tags:
                    object.tags.add(tag)
                tags = object.tags.all()
                form = None
        else:
            form = TagsForm(tags)

    context = {'object': object, 'tags': tags, 'form': form}

    context = converter.preprocess_context(context)

    output = render_to_string('core/ajax/tags_box',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)

    dajax.add_data({'target': target, 'content': output}, 'treeio.add_data')
    return dajax.json()
Esempio n. 5
0
def exedit(request, key, val):
    # fix key to match the attribute
    key = key.replace("id_", "")
    try:
        ex = Exercise.objects.get(pk=request.session["current_exercise"])
    except Exercise.DoesNotExist:
        print "ERROR -- Exercise not found in ajax.py"
        print "DEBUG {}".format(request.session["current_exercise"])
    setattr(ex, key, val)
    print "SET: {} - {}".format(key, val)
    ex.last_updated = datetime.datetime.now
    ex.save()
    dajax = Dajax()
    dajax.assign("#result", "value", "Data saved")
    return dajax.json()
Esempio n. 6
0
def gantt(request, task, start, end):
    dajax = Dajax()
    try:
            t = Task.objects.get(pk=task)
            ot = _("Task")
    except:
            t = Milestone.objects.get(pk=task)
            ot = _("Milestone")
    s = datetime.strptime(start,'%Y-%m-%d').replace(hour=12)
    e = datetime.strptime(end,'%Y-%m-%d').replace(hour=12)
    t.start_date = s
    t.end_date = e
    t.save()
    messages.add_message(request, messages.INFO, _("%s \"%s\" dates have been updated.")%(ot, unicode(t)))
    return dajax.json()
Esempio n. 7
0
def display_valid_contracts(request, host_id):
    dajax = Dajax()
    valid_contracts = Contract.objects.filter(start_date__lte=datetime.today(),
                                              end_date__gte=datetime.today())
    msg = "<strong>Valid contracts :</strong><table>"
    print str(valid_contracts)
    for contract in valid_contracts:
        msg += "<tr class='hosts_expand'><td>%s</td><td>" % contract
        msg += "<span onclick=\"Dajaxice.banquise.web.add_host_to_contract('Dajax.process',{'host_id':%s,'contract_id':%s});\">" % (
            host_id, contract.id)
        msg += "<img src='/media/images/icons/ok.png' height='16' border='0'></span></td></tr>"
    msg += "</table>"
    div_id = "#host_%s" % host_id
    dajax.assign(div_id, 'innerHTML', msg)
    return dajax.json()
Esempio n. 8
0
def tag(request, tag, method):
    try:
        ex = Exercise.objects.get(pk=request.session["current_exercise"])
    except Exercise.DoesNotExist:
        print "ERROR -- Exercise not found in ajax.py"
        print "DEBUG {}".format(request.session["current_exercise"])
    if method == "ADD":
        ex.tags.add(tag)
    elif method == "REMOVE":
        ex.tags.remove(tag)
    else:
        print "ERROR -- Unknown method: %s" % method
    dajax = Dajax()
    dajax.assign("#result", "value", "Data saved")
    return dajax.json()
Esempio n. 9
0
 def post(self, request, **kwargs):
     action = request.POST.get('action', None)
     
     self.dajax = Dajax()
     
     if action and action in self._rpc_methods:
         method = getattr(self, action)
         
         argv = request.POST.get('argv', None)
         
         if argv:
             argv = simplejson.loads(argv) or {}
             argv = dict((str(k), v) for k, v in argv.iteritems())
         else:
             argv = {}
         
         result = method(**argv)
         
         if result:
             if isinstance(result, GeneratorType):
                 result = list(result)
             
             jsn = simplejson.dumps(result)
         else:
             jsn = self.dajax.json()
         
         return self.get_json_response(jsn)
     
     raise Http404
Esempio n. 10
0
def gantt(request, task, start, end):
    dajax = Dajax()
    try:
        t = Task.objects.get(pk=task)
        ot = _("Task")
    except:
        t = Milestone.objects.get(pk=task)
        ot = _("Milestone")
    s = datetime.strptime(start, '%Y-%m-%d').replace(hour=12)
    e = datetime.strptime(end, '%Y-%m-%d').replace(hour=12)
    t.start_date = s
    t.end_date = e
    t.save()
    messages.add_message(
        request, messages.INFO,
        _("%s \"%s\" dates have been updated.") % (ot, unicode(t)))
    return dajax.json()
Esempio n. 11
0
def get_more(request, target='#more-news', skip=20):
    dajax = Dajax()

    profile = request.user.get_profile()
    query = _get_filter_query(profile) & (
        ~Q(author=profile) | Q(record_type='share') | Q(score__gt=0))
    updates = UpdateRecord.objects.filter(query).distinct()[skip:skip + 20]

    output = render_to_string('news/ajax/index', {
        'updates': updates,
        'skip': skip + 20
    },
                              context_instance=RequestContext(request),
                              response_format='html')

    dajax.add_data({'target': target, 'content': output}, 'treeio.add_data')
    return dajax.json()
Esempio n. 12
0
File: ajax.py Progetto: vovkd/treeio
def easy_invite(request, emails=None):

    dajax = Dajax()

    try:
        emails_original = emails
        emails = emails.split(',')

        sender = request.user.get_profile()
        default_group = sender.default_group
        domain = RequestSite(request).domain

        invited = []

        for email in emails:
            email = email.strip()
            if len(email) > 7 and re.match(
                    "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$",
                    email) != None:
                invitation = Invitation(sender=request.user.get_profile(),
                                        email=email,
                                        default_group=default_group)
                invitation.save()
                EmailInvitation(invitation=invitation,
                                sender=sender,
                                domain=domain).send_email()
                invited.append(email)

        if invited:
            template = 'core/tags/easy_invite_success'
        else:
            template = 'core/tags/easy_invite_failure'
    except:
        template = 'core/tags/easy_invite_failure'

    invite_markup = render_to_string(template, {},
                                     context_instance=RequestContext(request),
                                     response_format='html')

    dajax.add_data(
        {
            'target': "div.easy-invite[emails='%s']" % (emails_original),
            'content': invite_markup
        }, 'treeio.add_data')
    return dajax.json()
Esempio n. 13
0
def add_host_to_contract(request, host_id, contract_id):
    dajax = Dajax()
    host = Host.objects.get(id=host_id)
    contract = Contract.objects.get(id=contract_id)
    contract.hosts.add(host)
    contract.save()
    msg = ""
    div_id = "#img_host_%s" % host_id
    dajax.assign(div_id, 'innerHTML', msg)
    div_id = "#host_%s" % host_id
    dajax.assign(div_id, 'innerHTML', msg)
    return dajax.json()
Esempio n. 14
0
def consultaDetalleProduccion(request, nrec):
    #def consultaDetalleProduccion(ncab):
    dajax = Dajax()
    nrec = DetProcesos.objects.filter(cabprocesos=CabProcesos.objects.get(
        pk=ncab))[0].id
    raiz = DetProcesos.get_root(DetProcesos.objects.get(pk=nrec)).id
    size = DetProcesos.get_descendant_count(
        DetProcesos.objects.get(id=raiz)) + 1
    print raiz
    padre = DetProcesos.objects.get(id=raiz)
    cpadre = str(raiz)
    #Cabecera del Mensaje
    root = ET.Element("mxGraphModel")
    head = ET.SubElement(root, "root")
    ele = Element("mxCell")
    ele.set("id", "0")
    head.append(ele)
    ele1 = Element("mxCell")
    ele1.set("id", cpadre)
    ele1.set("parent", "0")
    head.append(ele1)
    objetoProcesos(head, str(raiz + 1), str(raiz + 1), str(raiz), str(raiz),
                   padre.descripcion)
    print padre.descripcion
    nid = raiz
    for ele in range(0, size - 1):
        obj = DetProcesos.get_children(DetProcesos.objects.get(id=nid))
        if len(obj) != 0:
            objetoProcesos(head, str(nid + 2), str(nid + 2), cpadre, cpadre,
                           obj.values()[0]['descripcion'])
            print obj.values()[0]['descripcion']
            nid = obj.values()[0]['id']

    nid = raiz
    cpadre = str(raiz + 1)
    for ele in range(0, size - 1):
        obj = DetProcesos.get_children(DetProcesos.objects.get(id=nid))
        if len(obj) != 0:
            nid = obj.values()[0]['id']
            dest = nid + 1
            enlaceProceso(
                head, str(nid + 2), str(nid + 2), str(raiz), str(raiz), cpadre,
                str(dest),
                TiposProcesos.objects.get(id=obj.values()[0]['tproceso_id']))
            cpadre = str(dest)

    valores = simplejson.dumps(ET.tostring(root), cls=JSONEncoder)
    #tree = ET.ElementTree(root)
    #tree.write("salida.xml")
    return valores
Esempio n. 15
0
def easy_invite(request, emails=None):

    dajax = Dajax()

    try:
        emails_original = emails
        emails = emails.split(',')

        sender = request.user.get_profile()
        default_group = sender.default_group
        domain = RequestSite(request).domain

        invited = []


        for email in emails:
            email = email.strip()
            if len(email) > 7 and re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
                invitation = Invitation(sender=request.user.get_profile(), email=email, default_group=default_group)
                invitation.save()
                EmailInvitation(invitation=invitation, sender=sender, domain=domain).send_email()
                invited.append(email)

        if invited:
            template = 'core/tags/easy_invite_success'
        else:
            template = 'core/tags/easy_invite_failure'
    except:
        template = 'core/tags/easy_invite_failure'

    invite_markup = render_to_string(template,
                                     {},
                                     context_instance=RequestContext(request),
                                     response_format='html')

    dajax.add_data({'target': "div.easy-invite[emails='%s']"%(emails_original), 'content': invite_markup}, 'treeio.add_data')
    return dajax.json()
Esempio n. 16
0
class RpcView(View):
    @classonlymethod
    def as_view(cls, **initkwargs):
        ret = super(RpcView, cls).as_view(**initkwargs)
        
        cls._rpc_methods = []
        
        for n in dir(cls):
            el = getattr(cls, n)
            
            if callable(el) and getattr(el, 'rpc_method', None):
                cls._rpc_methods.append(el.__name__)
        
        return ret
    
    def post(self, request, **kwargs):
        action = request.POST.get('action', None)
        
        self.dajax = Dajax()
        
        if action and action in self._rpc_methods:
            method = getattr(self, action)
            
            argv = request.POST.get('argv', None)
            
            if argv:
                argv = simplejson.loads(argv) or {}
                argv = dict((str(k), v) for k, v in argv.iteritems())
            else:
                argv = {}
            
            result = method(**argv)
            
            if result:
                if isinstance(result, GeneratorType):
                    result = list(result)
                
                jsn = simplejson.dumps(result)
            else:
                jsn = self.dajax.json()
            
            return self.get_json_response(jsn)
        
        raise Http404
    
    def get_json_response(self, content, **kwargs):
        return HttpResponse(content,
                            content_type='application/json',
                            **kwargs)
Esempio n. 17
0
File: ajax.py Progetto: vovkd/treeio
def attachment(request, object_id, update_id=None):
    dajax = Dajax()

    try:

        if object_id:
            attachments = Attachment.objects.filter(
                attached_object__id=object_id)
            template = 'core/tags/attachments_block'

            object_markup = render_to_string(
                template, {
                    'object_id': object_id,
                    'attachments': attachments
                },
                context_instance=RequestContext(request),
                response_format='html')

            dajax.add_data(
                {
                    'target': 'div.attachment-block[object="%s"]' % object_id,
                    'content': object_markup
                }, 'treeio.add_data')

        if update_id:
            attachments = Attachment.objects.filter(
                attached_record__id=update_id)
            template = 'core/tags/attachments_record_block'
            update_markup = render_to_string(
                template, {
                    'update_id': update_id,
                    'attachments': attachments
                },
                context_instance=RequestContext(request),
                response_format='html')
            dajax.add_data(
                {
                    'target':
                    'div.attachment-record-block[object="%s"]' % update_id,
                    'content': update_markup
                }, 'treeio.add_data')

    except Exception, e:
        print e
Esempio n. 18
0
File: ajax.py Progetto: vovkd/treeio
def comments_likes(request, target, form, expand=True):
    dajax = Dajax()

    response_format = 'html'

    object_id = form.get('object_id', 0)
    update = form.get('update', 0)
    object = None
    if update:
        object = UpdateRecord.objects.get(pk=object_id)
    else:
        object = Object.objects.get(pk=object_id)

    profile = request.user.get_profile()

    if object:
        if form.get('like', 0) == unicode(object.id):
            object.likes.add(profile)
            if hasattr(object, 'score'):
                object.score += 1
                object.save()

        elif form.get('unlike', 0) == unicode(object.id):
            object.likes.remove(profile)
            if hasattr(object, 'score'):
                object.score -= 1
                object.save()

        elif form.get('dislike', 0) == unicode(object.id):
            object.dislikes.add(profile)
            if hasattr(object, 'score'):
                object.score += 1
                object.save()

        elif form.get('undislike', 0) == unicode(object.id):
            object.dislikes.remove(profile)
            if hasattr(object, 'score'):
                object.score -= 1
                object.save()

        elif form.get('commentobject', 0) == unicode(
                object.id) and 'comment' in form:
            comment = Comment(author=profile, body=form.get('comment'))
            comment.save()
            if hasattr(object, 'score'):
                object.score += 1
                object.save()
            object.comments.add(comment)

    likes = object.likes.all()
    dislikes = object.dislikes.all()
    comments = object.comments.all()

    ilike = profile in likes
    idislike = profile in dislikes
    icommented = comments.filter(author=profile).exists() or \
                 comments.filter(author__default_group__in=[profile.default_group_id]+[i.id for i in profile.other_groups.all().only('id')]).exists()

    output = render_to_string('core/tags/comments_likes', {
        'object': object,
        'is_update': update,
        'profile': profile,
        'likes': likes,
        'dislikes': dislikes,
        'comments': comments,
        'ilike': ilike,
        'idislike': idislike,
        'icommented': icommented,
        'expand': expand
    },
                              context_instance=RequestContext(request),
                              response_format=response_format)

    dajax.add_data({'target': target, 'content': output}, 'treeio.add_data')
    return dajax.json()
Esempio n. 19
0
def user_books(request):
  dajax = Dajax()
  dajax.alert('the first book title is %s' % request.user.book_set.all()[0].title)
  return dajax.json()
Esempio n. 20
0
 def __init__(self,target,request):
     Dajax.__init__(self)
     self._target = target
     self._request = request
Esempio n. 21
0
 def __init__(self, target, request):
     Dajax.__init__(self)
     self._target = target
     self._request = request
Esempio n. 22
0
def addresses_by_user(request, user_id):
    addresses = Address.objects.filter(user__id=user_id)
    dajax = Dajax()
    dajax.alert("123")
    return dajax.json()
Esempio n. 23
0
def comments_likes(request, target, form, expand=True):
    dajax = Dajax()
        
    response_format = 'html'
    
    object_id = form.get('object_id', 0)
    update = form.get('update', 0)
    object = None
    if update:
        object = UpdateRecord.objects.get(pk=object_id)
    else:
        object = Object.objects.get(pk=object_id)
    
    profile  = request.user.get_profile()
    
    if object:
        if form.get('like', 0) == unicode(object.id):
            object.likes.add(profile)
            if hasattr(object, 'score'):
                object.score += 1
                object.save()
        
        elif form.get('unlike', 0) == unicode(object.id):
            object.likes.remove(profile)
            if hasattr(object, 'score'):
                object.score -= 1
                object.save()
            
        elif form.get('dislike', 0) == unicode(object.id):
            object.dislikes.add(profile)
            if hasattr(object, 'score'):
                object.score += 1
                object.save()
            
        elif form.get('undislike', 0) == unicode(object.id):
            object.dislikes.remove(profile)
            if hasattr(object, 'score'):
                object.score -= 1
                object.save()
        
        elif form.get('commentobject', 0) == unicode(object.id) and 'comment' in form:
            comment = Comment(author=profile,
                              body=form.get('comment'))
            comment.save()
            if hasattr(object, 'score'):
                object.score += 1
                object.save()
            object.comments.add(comment)
    
    likes      = object.likes.all()
    dislikes   = object.dislikes.all()
    comments   = object.comments.all()
    
    ilike      = profile in likes
    idislike   = profile in dislikes
    icommented = comments.filter(author=profile).exists() or \
                 comments.filter(author__default_group__in=[profile.default_group_id]+[i.id for i in profile.other_groups.all().only('id')]).exists()

    output = render_to_string('core/tags/comments_likes',
                               {'object': object,
                                'is_update': update,
                                'profile': profile,
                                'likes': likes,
                                'dislikes': dislikes,
                                'comments': comments,
                                'ilike': ilike,
                                'idislike': idislike,
                                'icommented': icommented,
                                'expand': expand },
                               context_instance=RequestContext(request),
                               response_format=response_format)
    
    dajax.add_data({'target': target, 'content': output}, 'treeio.add_data')
    return dajax.json()