Beispiel #1
0
def add_rendition():
    item = application.getItemByUUID(request.args(0))
    content = db.plugin_picture_info(item_id=item.unique_id)

    form = SQLFORM(db.plugin_picture_rendition)

    if form.process().accepted:
        r_id = form.vars.id
        rend = db.plugin_picture_rendition(r_id)
        (filename,
         stream) = db.plugin_picture_rendition.picture.retrieve(rend.picture)
        filename = stream.name
        im = Image.open(filename)
        # update rendition with image info
        rend.height = im.height
        rend.width = im.width
        rend.format = im.format
        rend.color = im.mode
        rend.update_record()
        # append this rendition to the item content
        content.renditions.append(r_id)
        content.update_record()
        redirect(application.getItemURL(item.unique_id))

    return locals()
Beispiel #2
0
def create():
    """Create a new organization"""
    tbl = db.organization
    tbl.users.readable = False
    tbl.users.writable = False
    tbl.desks.readable = False
    tbl.desks.writable = False
    tbl.name.requires = [
        IS_NOT_EMPTY(
            error_message=T("Cannot be empty")
        ),
        IS_NOT_IN_DB(
            db,
            'organization.name',
            error_message=T(
                "An Organization witch that name is allready in nStock"))]

    form = SQLFORM(tbl)
    form.add_button(T('Cancel'), URL('index'))

    if form.process().accepted:
        # add the new organization
        g_id = auth.user_group(auth.user.id)
        # give the user all perms over this org
        auth.add_permission(g_id, 'update', tbl, form.vars.id)
        auth.add_permission(g_id, 'read', tbl, form.vars.id)
        auth.add_permission(g_id, 'delete', tbl, form.vars.id)
        redirect(URL('index'))

    return locals()
Beispiel #3
0
def index():
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)

    short = request.vars.short if request.vars.short is not None else False

    tbl = db.plugin_comment_comment
    tbl.item_id.default = item.unique_id
    form = SQLFORM(
        tbl,
        submit_button=T('Comment'),
        formstyle='bootstrap3_stacked')

    rows = db(
        (tbl.id > 0) & (tbl.item_id == item.unique_id)
    ).select(orderby=~tbl.created_on)

    if form.process().accepted:
        response.js = "jQuery('#%s').get(0).reload();" % request.cid
        # send notifications to the users, except the current one
        subject = T("Comments on %s", (item.headline,))
        # get the comment body
        comment = tbl(form.vars.id)
        message = response.render(
            'plugin_comment/someone_commented.txt',
            dict(item=item, comment=comment, user=auth.user)
        )
        application.notifyCollaborators(
            item.unique_id,
            subject,
            message
        )

    return dict(form=form, comments=rows, short=short, item=item)
Beispiel #4
0
def add_rendition():
    item = application.getItemByUUID(request.args(0))
    content = db.plugin_picture_info(item_id=item.unique_id)

    form = SQLFORM(db.plugin_picture_rendition)

    if form.process().accepted:
        r_id = form.vars.id
        rend = db.plugin_picture_rendition(r_id)
        (filename, stream) = db.plugin_picture_rendition.picture.retrieve(
            rend.picture)
        filename = stream.name
        im = Image.open(filename)
        # update rendition with image info
        rend.height = im.height
        rend.width = im.width
        rend.format = im.format
        rend.color = im.mode
        rend.update_record()
        # append this rendition to the item content
        content.renditions.append(r_id)
        content.update_record()
        redirect(application.getItemURL(item.unique_id))

    return locals()
Beispiel #5
0
def index():
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)

    short = request.vars.short if request.vars.short is not None else False

    tbl = db.plugin_comment_comment
    tbl.item_id.default = item.unique_id
    form = SQLFORM(tbl,
                   submit_button=T('Comment'),
                   formstyle='bootstrap3_stacked')

    rows = db((tbl.id > 0) & (tbl.item_id == item.unique_id)).select(
        orderby=~tbl.created_on)

    if form.process().accepted:
        response.js = "jQuery('#%s').get(0).reload();" % request.cid
        # send notifications to the users, except the current one
        subject = T("Comments on %s", (item.headline, ))
        # get the comment body
        comment = tbl(form.vars.id)
        message = response.render(
            'plugin_comment/someone_commented.txt',
            dict(item=item, comment=comment, user=auth.user))
        application.notifyCollaborators(item.unique_id, subject, message)

    return dict(form=form, comments=rows, short=short, item=item)
Beispiel #6
0
def index():
    """
    Edit content
    """
    item = application.getItemByUUID(request.args(0))

    db.plugin_picture_info.thumbnail.readable = False
    db.plugin_picture_info.thumbnail.writable = False
    db.plugin_picture_info.renditions.readable = False
    db.plugin_picture_info.renditions.writable = False

    content = db.plugin_picture_info(item_id=item.unique_id)

    form = SQLFORM(
        db.plugin_picture_info,
        record=content,
        showid=False,
        submit_button=T('Save'))

    if form.process().accepted:
        application.notifyChanges(item.unique_id)
        application.indexItem(item.unique_id)
        response.flash = None

    return dict(form=form, item=item, content=content)
Beispiel #7
0
def getEditgameUpdateForm (game):
	"""
	Gets an update for the edit game page.

	Keyword Arguments:
	game -- row representing the current game

	Return Values:
	formUpdate -- web2py form
	"""

	from gluon import current, redirect, URL, SQLFORM
	db = current.db

	#Hide some fields of the form
	hideFields (db.game, ['id', 'host_id', 'game_status', 'password'])

	formUpdate = SQLFORM(db.game, game.id)
	formUpdate.add_class('assassins-form')

	if formUpdate.process().accepted:
		resizeImage(db.game, game.id)
		redirect(getUrl('edit', game.id))

	return formUpdate
def editform():
    """
    Return a sqlform object for editing the specified slide.
    """
    sid = session.plugin_slider_sid
    form = SQLFORM(db.plugin_slider_slides, sid,
                   separator='',
                   deletable=True,
                   showid=True)

    if form.process(formname='plugin_slider_slides/{}'.format(sid)).accepted:
        response.flash = 'The changes were recorded successfully.'
    elif form.errors:
        print('\n\nlistandedit form errors:')
        pprint({k: v for k, v in form.errors.items()})
        print('\n\nlistandedit form vars')
        pprint({k: v for k, v in form.vars.items()})
        print('\n\nlistandedit request vars')
        pprint({k: v for k, v in request.vars.items()})
        response.flash = 'Sorry, there was an error processing ' \
                         'the form. The changes have not been recorded.'

    else:
        pass

    return form
Beispiel #9
0
def create():
    """Create a new organization"""
    tbl = db.organization
    tbl.users.readable = False
    tbl.users.writable = False
    tbl.desks.readable = False
    tbl.desks.writable = False
    tbl.name.requires = [
        IS_NOT_EMPTY(error_message=T("Cannot be empty")),
        IS_NOT_IN_DB(
            db,
            'organization.name',
            error_message=T(
                "An Organization witch that name is allready in nStock"))
    ]

    form = SQLFORM(tbl)
    form.add_button(T('Cancel'), URL('index'))

    if form.process().accepted:
        # add the new organization
        g_id = auth.user_group(auth.user.id)
        # give the user all perms over this org
        auth.add_permission(g_id, 'update', tbl, form.vars.id)
        auth.add_permission(g_id, 'read', tbl, form.vars.id)
        auth.add_permission(g_id, 'delete', tbl, form.vars.id)
        redirect(URL('index'))

    return locals()
Beispiel #10
0
def inserir():
    u"""Permite inserir um novo registro.

    Um registro pode ser:
        - Uma notícia;
        - Um evento;
        - Um produto;
        - Um membro;
        - Um apoiador.
    Observação: Somente usuários com permissão de admin podem inserir novos
    membros e apoiadores.
    """
    argumento = current.request.args(0) or redirect(URL('default', 'index'))
    lista_tabelas = ['noticias', 'eventos', 'produtos']
    auth = current.globalenv['auth']
    db = current.globalenv['db']
    if auth.has_membership('admin'):
        lista_tabelas.extend(['membros', 'apoiadores'])
    if argumento not in lista_tabelas:
        current.session.flash = current.T(
            'Operação não permitida a seu usuário.'
        )
        redirect(URL('admin', 'listar', args='noticias'))
    form = SQLFORM(
        db[argumento], submit_button="Enviar",
        formstyle='bootstrap3_stacked')
    if form.process().accepted:
        current.response.flash = 'Registro inserido com sucesso!'
    elif form.errors:
        current.response.flash = 'Formulário contem erros'
    return {'argumento': argumento, 'form': form}
Beispiel #11
0
def getEditgameUpdateForm(game):
    """
	Gets an update for the edit game page.

	Keyword Arguments:
	game -- row representing the current game

	Return Values:
	formUpdate -- web2py form
	"""

    from gluon import current, redirect, URL, SQLFORM
    db = current.db

    #Hide some fields of the form
    hideFields(db.game, ['id', 'host_id', 'game_status', 'password'])

    formUpdate = SQLFORM(db.game, game.id)
    formUpdate.add_class('assassins-form')

    if formUpdate.process().accepted:
        resizeImage(db.game, game.id)
        redirect(getUrl('edit', game.id))

    return formUpdate
Beispiel #12
0
def create():
    org = db.organization(session.org_id)
    tbl = db.desk
    tbl.item_list.readable = False
    tbl.item_list.writable = False
    tbl.name.requires = IS_NOT_EMPTY()

    form = SQLFORM(db.desk)
    form.add_button(T('Cancel'), URL('org', 'view', args=[org.id]))

    if form.process().accepted:
        # add the new desk to the org list
        desk_id = form.vars.id
        # add current users as the one with permission to update manage
        # this desk
        auth.add_permission(
            auth.user_group(auth.user.id),
            'update',
            db.desk,
            desk_id)
        desk_list = org.desks
        desk_list.insert(0, desk_id)
        org.update_record(desks=desk_list)
        # return to the org desk list
        redirect(URL('org', 'view', args=[org.id]))

    return locals()
Beispiel #13
0
def inserir():
    """Insere um novo banner."""
    db = current.globalenv['db']
    form = SQLFORM(
        db.carousel, submit_button="Enviar",
        formstyle='bootstrap3_stacked')
    if form.process().accepted:
        current.response.flash = 'Registro inserido com sucesso!'
    elif form.errors:
        current.response.flash = 'Formulário contem erros'
    return {'form': form}
Beispiel #14
0
def edit():
    dash = db.dashboard(request.args(0))
    db.dashboard.item_list.readable = False
    db.dashboard.item_list.writable = False

    form = SQLFORM(db.dashboard, record=dash, showid=False)

    if form.process().accepted:
        redirect(URL('index', args=[dash.id]))

    return locals()
Beispiel #15
0
def edit():
    desk = db.desk(request.args(0))
    session.desk_id = desk.id

    db.desk.item_list.readable = False
    db.desk.item_list.writable = False
    form = SQLFORM(db.desk, record=desk, showid=False)

    if form.process().accepted:
        redirect(URL('index', args=[desk.id]))

    return locals()
Beispiel #16
0
def edit():
    desk = db.desk(request.args(0))
    session.desk_id = desk.id

    db.desk.item_list.readable = False
    db.desk.item_list.writable = False
    form = SQLFORM(db.desk, record=desk, showid=False)

    if form.process().accepted:
        redirect(URL('index', args=[desk.id]))

    return locals()
Beispiel #17
0
def index():
    """
    Edit/Show package content
    """
    pkg_item = application.getItemByUUID(request.args(0))
    content = db.plugin_package_content(item_id=pkg_item.unique_id)

    form = SQLFORM(db.plugin_package_content, record=content, showid=False)

    if form.process().accepted:
        application.indexItem(pkg_item.unique_id)
        redirect(URL('default', 'index'))

    return locals()
Beispiel #18
0
def edit():
    org = db.organization(request.args(0))
    tbl = db.organization
    tbl.users.readable = False
    tbl.users.writable = False
    tbl.desks.readable = False
    tbl.desks.writable = False
    tbl.name.requires = [IS_NOT_EMPTY()]

    # edit form
    form = SQLFORM(db.organization, record=org, showid=False)
    if form.process().accepted:
        redirect(URL('view', args=[org.id]))

    return locals()
Beispiel #19
0
def edit():
    org = db.organization(request.args(0))
    tbl = db.organization
    tbl.users.readable = False
    tbl.users.writable = False
    tbl.desks.readable = False
    tbl.desks.writable = False
    tbl.name.requires = [IS_NOT_EMPTY()]

    # edit form
    form = SQLFORM(db.organization, record=org, showid=False)
    if form.process().accepted:
        redirect(URL('view', args=[org.id]))

    return locals()
Beispiel #20
0
def meta():
    """
    Edit/Show item metadata info
    """
    item = application.getItemByUUID(request.args(0))

    if item is None:
        raise HTTP(404)

    contentType = application.getContentType(item.item_type)
    l_names = [
        (r.language_tag, r.english_name) for r in db(
            db.languages.id > 0
        ).select(orderby=db.languages.english_name)
    ]
    db.item.language_tag.requires = IS_IN_SET(
        l_names,
        zero=None
    )

    # issue #5 hidde some fields from metadata
    db.item.provider.readable = False
    db.item.provider.writable = False
    db.item.provider_service.readable = False
    db.item.provider_service.writable = False
    db.item.copyright_holder.readable = False
    db.item.copyright_holder.writable = False
    db.item.copyright_url.readable = False
    db.item.copyright_url.writable = False
    db.item.copyright_notice.readable = False
    db.item.copyright_notice.writable = False
    db.item.pubstatus.readable = False
    db.item.pubstatus.writable = False

    form = SQLFORM(db.item, record=item)

    if form.process().accepted:
        # session.flash = "Done !"
        # send an email to all the users who has access to this item
        application.notifyChanges(item.unique_id)
        application.indexItem(item.unique_id)
        if request.ajax:
            response.js = "$('#metaModal').modal('hide');"
        else:
            redirect(application.getItemURL(item.unique_id))

    return locals()
Beispiel #21
0
def linked_create_form():
    """
    creates a form to insert a new entry into the linked table which populates
    the ajaxSelect widget
    """
    print 'Starting linked_create_form'
    try:
        tablename = request.args[0]
        fieldname = request.args[1]
        wrappername = request.vars['wrappername']
        table = db[tablename]
        field = table[fieldname]

        linktable = get_linktable(field)

        formname = '{}_create'.format(wrappername)
        form = SQLFORM(db[linktable])

        comp_url = URL('plugin_ajaxselect', 'set_widget.load',
                    args=[tablename, fieldname],
                    vars=request.vars)

        if form.process(formname=formname).accepted:
            response.flash = 'form accepted'
            response.js = "window.setTimeout(" \
                          "web2py_component('{}', '{}'), " \
                          "500);".format(comp_url, wrappername)

            print 'linked create form accepted'
            print 'linked create form vars:'
            pprint(form.vars)
        if form.errors:
            response.error = 'form was not processed'
            response.flash = 'form was not processed'
            print 'error processing linked_create_form'
            print form.errors
        else:
            print 'form not processed but no errors'
            pass

    except Exception:
        import traceback
        print traceback.format_exc(5)
        form = traceback.format_exc(5)

    return dict(form=form)
Beispiel #22
0
def index():
    """
    Edit/Show package content
    """
    pkg_item = application.getItemByUUID(request.args(0))
    content = db.plugin_package_content(item_id=pkg_item.unique_id)

    form = SQLFORM(
        db.plugin_package_content,
        record=content,
        showid=False)

    if form.process().accepted:
        application.indexItem(pkg_item.unique_id)
        redirect(URL('default', 'index'))

    return locals()
Beispiel #23
0
def create_grade():
    """
    TODO: Make sure these fields are all required.
    TODO: Restrict names in drop-down to students in current course
    TODO: Remove logged-in student from name drop-down
    """
    c = ''
    if request.args:
        c = db.courses[request.args[0]]
    else:
        redirect(URL('index'))
    cname = c.course_name
    cnum = c.id
    m = str(c.max_score)
    if m in [None, 'None']:
        m = '10'

    class_members = db(db.course_membership.course == cnum).select()
    member_nums = [member['id'] for member in class_members]
    print 'member_nums', member_nums
    mquery = db(db.auth_user.id.belongs(
                    db(db.course_membership.course == cnum)._select(db.course_membership.name)
                                        ))
    db.grades.name.requires = IS_IN_DB(mquery, 'auth_user.id', '%(last_name)s, %(first_name)s')
    form = SQLFORM(
        db.grades,
        separator='',
        fields=['name', 'grade', 'class_date'],
        labels={'name': "Student's name",
                'grade': "Grade",
                'class_date': 'Class date'},
        col3={'name': 'The student to receive the grade.',
              'grade': 'a number out of {}'.format(m),
              'class_date': "the date when the class took place"},
        submit_button='assign this grade'
        )
    form.vars.course = cnum
    if form.process().accepted:
        response.flash = 'Thanks! The grade was recorded.'

    the_user = db(db.auth_user.id == auth.user_id).select().first()
    fn = the_user.first_name
    return dict(form=form,
                fn=fn,
                cname=cname,
                courseid=cnum)
Beispiel #24
0
def editar():
    """Deleta ou edita um banner modificando seus atributos."""
    cod = current.request.args(0, cast=int, otherwise=URL('default', 'index'))
    db = current.globalenv['db']
    form = SQLFORM(
        db.carousel,
        cod,
        deletable=True,
        showid=False, submit_button="Enviar",
        upload=URL('default', 'download'), formstyle="bootstrap3_stacked"
    )

    if form.process().accepted:
        current.session.flash = 'Registro editado com sucesso'
        redirect(URL('banners', 'listar'))
    elif form.errors:
        current.session.flash = 'Formulário contem erros'
    return {'form': form}
def edit_form():
    item = application.getItemByUUID(request.args(0))
    content = db.plugin_photoset_content(item_id=item.unique_id)

    db.plugin_photoset_content.photoset.readable = False
    db.plugin_photoset_content.photoset.writable = False
    db.plugin_photoset_content.item_id.readable = False
    db.plugin_photoset_content.item_id.writable = False

    form = SQLFORM(db.plugin_photoset_content,
                   record=content,
                   showid=False,
                   submit_button=T('Save'))

    if form.process().accepted:
        application.notifyChanges(item.unique_id)
        application.indexItem(item.unique_id)
        response.flash = T('Saved')

    return form
def addform():
    """
    Return a sqlform object for editing the specified slide.
    """
    did = request.args[0]
    direction = request.vars.direction
    sid = session.plugin_slider_sid
    deckorder = session.plugin_slider_deckorder
    # get index for inserting new slide
    sindex = deckorder.index(sid)
    newindex = sindex + 1
    if newindex == len(deckorder) or direction == 'before':
        newindex = sindex

    form = SQLFORM(db.plugin_slider_slides,
                   separator='',
                   deletable=True,
                   showid=True,
                   formname='plugin_slider_slides/addnew')
    if form.process(formname='plugin_slider_slides/addnew').accepted:
        deckrow = db.plugin_slider_decks(did)
        # TODO: is this the best way to get the new slide id?
        slideid = db(db.plugin_slider_slides).select().last().id
        deckslides = deckrow.deck_slides
        deckslides.insert(sindex, slideid)
        deckrow.update_record(deck_slides=deckslides)
        response.flash = 'The new slide was added successfully.'
    elif form.errors:
        print('\n\nlistandedit form errors:')
        pprint({k: v for k, v in form.errors.items()})
        print('\n\nlistandedit form vars')
        pprint({k: v for k, v in form.vars.items()})
        print('\n\nlistandedit request vars')
        pprint({k: v for k, v in request.vars.items()})
        response.flash = 'Sorry, there was an error processing ' \
                         'the form. The changes have not been recorded.'

    else:
        pass

    return form
Beispiel #27
0
def meta():
    """
    Edit/Show item metadata info
    """
    item = application.getItemByUUID(request.args(0))

    if item is None:
        raise HTTP(404)

    contentType = application.getContentType(item.item_type)
    l_names = [(r.language_tag, r.english_name) for r in db(
        db.languages.id > 0).select(orderby=db.languages.english_name)]
    db.item.language_tag.requires = IS_IN_SET(l_names, zero=None)

    # issue #5 hidde some fields from metadata
    db.item.provider.readable = False
    db.item.provider.writable = False
    db.item.provider_service.readable = False
    db.item.provider_service.writable = False
    db.item.copyright_holder.readable = False
    db.item.copyright_holder.writable = False
    db.item.copyright_url.readable = False
    db.item.copyright_url.writable = False
    db.item.copyright_notice.readable = False
    db.item.copyright_notice.writable = False
    db.item.pubstatus.readable = False
    db.item.pubstatus.writable = False

    form = SQLFORM(db.item, record=item)

    if form.process().accepted:
        # session.flash = "Done !"
        # send an email to all the users who has access to this item
        application.notifyChanges(item.unique_id)
        application.indexItem(item.unique_id)
        if request.ajax:
            response.js = "$('#metaModal').modal('hide');"
        else:
            redirect(application.getItemURL(item.unique_id))

    return locals()
Beispiel #28
0
def linked_edit_form():
    """
    creates a form to edit, update, or delete an intry in the linked table which
    populates the AjaxSelect widget.
    """
    try:
        tablename = request.args[0]
        fieldname = request.args[1]
        table = db[tablename]
        field = table[fieldname]

        linktable = get_linktable(field)

        this_row = request.args[2]
        wrappername = request.vars['wrappername']
        formname = '{}/edit'.format(tablename)

        form = SQLFORM(db[linktable], this_row)

        comp_url = URL('plugin_ajaxselect',
                       'set_widget.load',
                       args=[tablename, fieldname],
                       vars=request.vars)

        if form.process(formname=formname).accepted:
            response.flash = 'form accepted'
            response.js = "web2py_component('%s', '%s');" % (comp_url,
                                                             wrappername)
        if form.errors:
            response.error = 'form was not processed'
            print('error processing linked_create_form')
            print(form.errors)
        else:
            pass
    except Exception:
        import traceback
        print('error in whole of linked_edit_form')
        print(traceback.format_exc(5))
        form = traceback.format_exc(5)

    return {'form': form}
def linked_edit_form():
    """
    creates a form to edit, update, or delete an intry in the linked table which
    populates the AjaxSelect widget.
    """
    try:
        tablename = request.args[0]
        fieldname = request.args[1]
        table = db[tablename]
        field = table[fieldname]

        req = field.requires if isinstance(field.requires, list) else [field.requires]
        linktable = req[0].ktable

        this_row = request.args[2]
        wrappername = request.vars['wrappername']
        formname = '{}/edit'.format(tablename)

        form = SQLFORM(db[linktable], this_row)

        comp_url = URL('plugin_ajaxselect', 'set_widget.load',
                       args=[tablename, fieldname],
                       vars=request.vars)

        if form.process(formname=formname).accepted:
            response.flash = 'form accepted'
            response.js = "web2py_component('%s', '%s');" % (comp_url, wrappername)
        if form.errors:
            response.error = 'form was not processed'
            print 'error processing linked_create_form'
            print form.errors
        else:
            pass
    except Exception:
        import traceback
        print 'error in whole of linked_edit_form'
        print traceback.format_exc(5)
        form = traceback.format_exc(5)

    return {'form': form}
Beispiel #30
0
def edit_form():
    item = application.getItemByUUID(request.args(0))
    content = db.plugin_photoset_content(item_id=item.unique_id)

    db.plugin_photoset_content.photoset.readable = False
    db.plugin_photoset_content.photoset.writable = False
    db.plugin_photoset_content.item_id.readable = False
    db.plugin_photoset_content.item_id.writable = False

    form = SQLFORM(
        db.plugin_photoset_content,
        record=content,
        showid=False,
        submit_button=T('Save')
    )

    if form.process().accepted:
        application.notifyChanges(item.unique_id)
        application.indexItem(item.unique_id)
        response.flash = T('Saved')

    return form
Beispiel #31
0
def index():
    """
    Edit content
    """
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)

    content = db.plugin_text_text(item_id=item.unique_id)

    form = SQLFORM(db.plugin_text_text,
                   record=content,
                   showid=False,
                   submit_button=T('Save'))

    if form.process().accepted:
        application.notifyChanges(item.unique_id)
        application.indexItem(item.unique_id)
        redirect(application.getItemURL(item.unique_id))
        response.flash = T('Done')

    return dict(form=form, item=item, content=content)
Beispiel #32
0
def add_rendition():
    item = application.getItemByUUID(request.args(0))
    content = db.plugin_picture_info(item_id=item.unique_id)
    db.plugin_picture_rendition.thumbnail.writable = False
    db.plugin_picture_rendition.thumbnail.readable = False

    form = SQLFORM(db.plugin_picture_rendition)

    if form.process().accepted:
        r_id = form.vars.id
        rend = db.plugin_picture_rendition(r_id)
        (filename, stream) = db.plugin_picture_rendition.picture.retrieve(
            rend.picture)
        filename = stream.name
        im = Image.open(filename)
        # update rendition with image info
        rend.width, rend.height = im.size
        rend.format = im.format
        rend.color = im.mode
        rend.update_record()
        # --------------------------------
        size = (700, 700)
        im.thumbnail(size)
        fl = NamedTemporaryFile(suffix=".jpg", delete=True)
        fl.close()
        im.save(fl.name, "JPEG")
        store_tumb = db.plugin_picture_rendition.thumbnail.store(
            open(fl.name, 'rb'), fl.name)
        os.unlink(fl.name)  # cleanup
        rend.update_record(
            thumbnail=store_tumb
        )
        # append this rendition to the item content
        content.renditions.append(r_id)
        content.update_record()
        redirect(application.getItemURL(item.unique_id))

    return locals()
Beispiel #33
0
def index():
    """
    Edit content
    """
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)

    content = db.plugin_text_text(item_id=item.unique_id)

    form = SQLFORM(
        db.plugin_text_text,
        record=content,
        showid=False,
        submit_button=T('Save'))

    if form.process().accepted:
        application.notifyChanges(item.unique_id)
        application.indexItem(item.unique_id)
        redirect(application.getItemURL(item.unique_id))
        response.flash = T('Done')

    return dict(form=form, item=item, content=content)
Beispiel #34
0
def index():
    """
    Edit content
    """
    item = application.getItemByUUID(request.args(0))

    db.plugin_picture_info.renditions.readable = False
    db.plugin_picture_info.renditions.writable = False

    content = db.plugin_picture_info(item_id=item.unique_id)

    form = SQLFORM(
        db.plugin_picture_info,
        record=content,
        showid=False,
        submit_button=T('Save'))

    if form.process().accepted:
        application.notifyChanges(item.unique_id)
        application.indexItem(item.unique_id)
        response.flash = None

    return dict(form=form, item=item, content=content)
Beispiel #35
0
    def comment_internal(self):
        is_author = False
        if self.session.auth and self.session.auth.user:
            is_author = True if self.session.auth.user.id == self.context.article.author else False
            self.db.Comments.article_id.default = self.context.article.id
            self.db.Comments.user_id.default = self.session.auth.user.id
            self.db.Comments.commenttime.default = self.request.now
            self.db.Comments.comment_text.label = self.T("Post your comment")
            from plugin_ckeditor import CKEditor

            ckeditor = CKEditor()
            self.db.Comments.comment_text.widget = ckeditor.basicwidget
            form = SQLFORM(self.db.Comments, formstyle="divs")
            if form.process(message_onsuccess=self.T("Comment included")).accepted:
                self.new_article_event(
                    "new_article_comment",
                    self.session.auth.user,
                    data={
                        "event_text": form.vars.comment_text,
                        "event_link": "%s/%s#comment_%s"
                        % (self.context.article.id, self.context.article.slug, form.vars.id),
                    },
                )
        else:
            form = A(
                self.T("Login to post comments"),
                _class="button",
                _href=self.CURL(
                    "default",
                    "user",
                    args="login",
                    vars=dict(
                        _next=self.CURL("article", "show", args=[self.context.article.id, self.context.article.slug])
                    ),
                ),
            )

        comments = self.db(self.db.Comments.article_id == self.context.article.id).select(
            orderby=self.db.Comments.created_on
        )

        if comments and is_author:
            edit_in_place = ckeditor.bulk_edit_in_place(
                ["comment_%(id)s" % comment for comment in comments], URL("editcomment")
            )
        elif comments and self.session.auth and self.session.auth.user:
            usercomments = comments.find(lambda row: row.user_id == self.session.auth.user.id)
            if usercomments:
                edit_in_place = ckeditor.bulk_edit_in_place(
                    ["comment_%(id)s" % comment for comment in usercomments], URL("editcomment")
                )
            else:
                edit_in_place = ("", "")
        else:
            edit_in_place = ("", "")

        return DIV(
            H4(
                IMG(_src=URL("static", "%s/images/icons" % self.context.theme_name, args="board.24.png")),
                self.T("Comments"),
            ),
            UL(
                *[
                    LI(
                        H5(
                            A(
                                self.T(
                                    "%s %s" % (comment.nickname or comment.user_id, self.db.pdate(comment.commenttime))
                                ),
                                _href=self.CURL("person", "show", args=comment.nickname or comment.user_id),
                            )
                        ),
                        DIV(
                            XML(comment.comment_text),
                            **{
                                "_class": "editable commentitem",
                                "_data-object": "comment",
                                "_data-id": comment.id,
                                "_id": "comment_%s" % comment.id,
                            }
                        ),
                        _class="comment_li",
                    )
                    for comment in comments
                ],
                **dict(_class="comment_ul")
            ),
            edit_in_place[1],
            form,
            _class="internal-comments article-box",
        )
Beispiel #36
0
    def comment_internal(self):
        is_author = False
        if self.session.auth and self.session.auth.user:
            is_author = True if self.session.auth.user.id == self.context.article.author else False
            self.db.Comments.article_id.default = self.context.article.id
            self.db.Comments.user_id.default = self.session.auth.user.id
            self.db.Comments.commenttime.default = self.request.now
            self.db.Comments.comment_text.label = self.T("Post your comment")
            from plugin_ckeditor import CKEditor
            ckeditor = CKEditor()
            self.db.Comments.comment_text.widget = ckeditor.basicwidget
            form = SQLFORM(self.db.Comments, formstyle='divs')
            submit_button = form.elements(_type='submit')[0]
            submit_button['_class'] = "btn btn-info"
            submit_button['_value'] = self.T("Post comment")
            if form.process(message_onsuccess=self.T('Comment included')).accepted:
                self.new_article_event('new_article_comment',
                                        self.session.auth.user,
                                        data={'event_text': form.vars.comment_text,
                                              'event_link': form.vars.nickname or form.vars.user_id,
                                              'event_image': self.get_image(None, 'user', themename=self.context.theme_name, user=self.session.auth.user),
                                              'event_link_to': "%s/%s#comment_%s" % (self.context.article.id, self.context.article.slug, form.vars.id)})

        else:
            form = CAT(A(self.T("Login to post comments"),
                     _class="button btn",
                     _href=self.CURL('default', 'user',
                                  args='login',
                                  vars=dict(_next=self.CURL('article', 'show',
                                       args=[self.context.article.id,
                                             self.context.article.slug])))),
                       BR(),
                       BR())

        if 'commentlimitby' in self.request.vars:
            limitby = [int(item) for item in self.request.vars.commentlimitby.split(',')]
        else:
            limitby = (0, 5)
        comment_set = self.db(self.db.Comments.article_id == self.context.article.id)
        comments = comment_set.select(orderby=~self.db.Comments.created_on, limitby=limitby)

        if comments and is_author:
            edit_in_place = ckeditor.bulk_edit_in_place(["comment_%(id)s" % comment for comment in comments], URL('editcomment'))
        elif comments and self.session.auth and self.session.auth.user:
            usercomments = comments.find(lambda row: row.user_id == self.session.auth.user.id)
            if usercomments:
                edit_in_place = ckeditor.bulk_edit_in_place(["comment_%(id)s" % comment for comment in usercomments], URL('editcomment'))
            else:
                edit_in_place = ('', '')
        else:
            edit_in_place = ('', '')

        self.context.lencomments = comment_set.count()

        def showmore(anchor, limitby=limitby, lencomments=self.context.lencomments):
            if lencomments > limitby[1]:
                return A(self.T('show more comments'), _class="button btn", _style="width:97%;", _href=self.CURL(args=self.request.args, vars={"commentlimitby": "0,%s" % (limitby[1] + 10)}, anchor=anchor))
            else:
                return ''

        return DIV(
                  H4(IMG(_src=URL('static', '%s/images/icons' % self.context.theme_name, args='board.24.png')), self.T("Comments"), " (%s)" % self.context.lencomments),
                  UL(form,
                      *[LI(
                           H5(
                              A(
                                 self.T("%s %s", (comment.nickname or comment.user_id,
                                                   self.db.pdate(comment.commenttime))),
                               _href=self.CURL('person', 'show', args=comment.nickname or comment.user_id))
                             ),
                            DIV(
                               XML(comment.comment_text),
                               **{'_class': 'editable commentitem',
                                  '_data-object': 'comment',
                                  '_data-id': comment.id,
                                  '_id': "comment_%s" % comment.id}
                             ),
                            _class="comment_li"
                          ) for comment in comments],
                  **dict(_class="comment_ul")),
                  edit_in_place[1],
                  showmore("comment_%s" % comment.id) if comments else '',
                  _class="internal-comments article-box"
                  )
    def dupform(self, rargs=None, rvars=None, copylabel=None,
                deletable=True, showid=True, dbio=True, formstyle='ul'):
        """
        """
        db = current.db
        rjs = ''
        flash = ''
        duplink = ''
        tablename = rargs[0]
        rowid = rargs[1]
        orderby = rvars['orderby'] or 'id'
        restrictor = rvars['restrictor'] or None
        collation = rvars['collation'] or None
        postprocess = rvars['postprocess'] or None
        copylabel = copylabel if copylabel else 'Make a copy of this record'
        dbio = False if 'dbio' in list(rvars.keys()) and rvars['dbio'] == 'False' else True

        # create a link for adding a new row to the table
        duplink = A(copylabel,
                    _href=URL('plugin_listandedit',
                                'dupAndEdit.load',
                                args=[tablename, rowid],
                                vars=rvars),
                    _class='plugin_listandedit_duplicate',
                    cid='viewpane')

        formname = '{}/{}/dup'.format(tablename, rowid)

        src = db(db[tablename].id == rowid).select().first()
        form = SQLFORM(db[tablename],
                       separator='',
                       deletable=deletable,
                       showid=showid,
                       formstyle=formstyle)

        for v in db[tablename].fields:
            # on opening populate duplicate values
            form.vars[v] = src[v] if v != 'id' and v in src else None
            # FIXME: ajaxselect field values have to be added manually
            if db[tablename].fields[1] in list(rvars.keys()):  # on submit add ajaxselect values
                extras = [f for f in db[tablename].fields
                        if f not in list(form.vars.keys())]
                for e in extras:
                    form.vars[e] = rvars[e] if e in list(rvars.keys()) else ''
        del form.vars['id']
        # print 'form vars ========================================='
        # pprint(form.vars)

        if form.process(formname=formname, dbio=dbio).accepted:
            db.commit()
            #print 'accepted form ================================='
            the_url = URL('plugin_listandedit', 'itemlist.load',
                          args=[tablename], vars={'orderby': orderby,
                                                  'restrictor': restrictor,
                                                  'collation': collation,
                                                  'postprocess': postprocess})
            rjs = "web2py_component('{}', 'listpane');".format(the_url)
            if dbio:
                flash = 'New record successfully created.'
        elif form.errors:
            print('listandedit form errors:', [e for e in form.errors])
            print('listandedit form vars:', form.vars)
            flash = 'Sorry, there was an error processing '\
                            'the form. The new record has not been created.'
        else:
            pass

        return form, duplink, flash, rjs
Beispiel #38
0
    def comment_internal(self):
        is_author = False
        if self.session.auth and self.session.auth.user:
            is_author = True if self.session.auth.user.id == self.context.article.author else False
            self.db.Comments.article_id.default = self.context.article.id
            self.db.Comments.user_id.default = self.session.auth.user.id
            self.db.Comments.commenttime.default = self.request.now
            self.db.Comments.comment_text.label = self.T("Post your comment")
            from plugin_ckeditor import CKEditor
            ckeditor = CKEditor()
            self.db.Comments.comment_text.widget = ckeditor.basicwidget
            form = SQLFORM(self.db.Comments, formstyle='divs')
            if form.process(
                    message_onsuccess=self.T('Comment included')).accepted:
                self.new_article_event(
                    'new_article_comment',
                    self.session.auth.user,
                    data={
                        'event_text':
                        form.vars.comment_text,
                        'event_link':
                        "%s/%s#comment_%s" %
                        (self.context.article.id, self.context.article.slug,
                         form.vars.id)
                    })
        else:
            form = A(
                self.T("Login to post comments"),
                _class="button",
                _href=self.CURL(
                    'default',
                    'user',
                    args='login',
                    vars=dict(_next=self.CURL('article',
                                              'show',
                                              args=[
                                                  self.context.article.id,
                                                  self.context.article.slug
                                              ]))))

        comments = self.db(
            self.db.Comments.article_id == self.context.article.id).select(
                orderby=self.db.Comments.created_on)

        if comments and is_author:
            edit_in_place = ckeditor.bulk_edit_in_place(
                ["comment_%(id)s" % comment for comment in comments],
                URL('editcomment'))
        elif comments and self.session.auth and self.session.auth.user:
            usercomments = comments.find(
                lambda row: row.user_id == self.session.auth.user.id)
            if usercomments:
                edit_in_place = ckeditor.bulk_edit_in_place(
                    ["comment_%(id)s" % comment for comment in usercomments],
                    URL('editcomment'))
            else:
                edit_in_place = ('', '')
        else:
            edit_in_place = ('', '')

        return DIV(H4(
            IMG(_src=URL('static',
                         '%s/images/icons' % self.context.theme_name,
                         args='board.24.png')), self.T("Comments")),
                   UL(
                       *[
                           LI(H5(
                               A(self.T("%s %s" %
                                        (comment.nickname or comment.user_id,
                                         self.db.pdate(comment.commenttime))),
                                 _href=self.CURL('person',
                                                 'show',
                                                 args=comment.nickname
                                                 or comment.user_id))),
                              DIV(
                                  XML(comment.comment_text), **{
                                      '_class': 'editable commentitem',
                                      '_data-object': 'comment',
                                      '_data-id': comment.id,
                                      '_id': "comment_%s" % comment.id
                                  }),
                              _class="comment_li") for comment in comments
                       ], **dict(_class="comment_ul")),
                   edit_in_place[1],
                   form,
                   _class="internal-comments article-box")