If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

For this example let's imagine we want to create some pages for our website.

A page has a title, and a content. We want to allow users to edit a page with a wysiwyg editor, and add images with the editor. We ill use NicEdit editor + nicupload plugin. Nicedit will be installed in myApp/static folder

Let's download it  : http://nicedit.com/download.php 

 

 
 

1) We create the page table in our model file (db.py)

db.define_table('page',
    Field('title', unique=True, notnull=True, label=T('Title')),
    Field('content', 'text', label=T('Content'))
    format='%(title)s'
)

 

2) We need a controller to edit the pages : edit_page

@auth.requires_membership('manager') #access restricted to manager users only
def edit_page():
    page_id = request.args(0)
    page = db.page(page_id)
    if len(request.args) and page:  
        crud.settings.update_deletable = False
        form = crud.update(db.page,page,next=URL('show_page', args=page.id))
    else:
        form = crud.create(db.page,next='edit_page/[id]')
    return dict(form=form)

3) Now we create a view file. The view will receive a form object from the controller. db.page.content will be represented by a textarea field.

<script type="text/javascript" src="{{=URL('static', 'nicEdit/nicEditComplete.js')}}"></script>
    <script type="text/javascript">
    bkLib.onDomLoaded(function() { 
        new nicEditors.allTextAreas({
            iconsPath :"{{=URL('static', 'nicEdit/nicEditorIcons.gif')}}",
	    buttonList : ['bold','italic','underline','strikeThrough','left', 'center',
	    'right', 'justify', 'ol', 'ul', 'fontSize', 'fontFormat', 'indent', 'outdent', 'link', 'upload'],
	    uploadURI : "{{=URL('default', 'nicedit_image_upload', args=request.args(0))}}",
	})
    });
    </script>
de</script>

UploadURI parameter will call 'nicedit_image_upload' function, in 'default' controller and send the page_id as an argument.

 

3) Now we create 'nicedit_image_upload' function :

def nicedit_image_upload():
    """
    Controller to upload images with nicedit
    """
    from gluon.contrib.simplejson import dumps
    from os import mkdir

    page_id = request.args(0)
    pathname = path.join(request.folder,'static','images', 'pages_content', page_id)
    #Images will be uploaded in static/images/pages_content/[page_id]/
    if not path.exists(pathname):
        mkdir(pathname)

    pathfilename = path.join(pathname, request.vars.image.filename)
    dest_file = open(pathfilename, 'wb')
    
    try:
        dest_file.write(request.vars.image.file.read())
    finally:
        dest_file.close()

    links_dict = {"original":URL('static', 'images/pages_content/'+page_id+'/'+request.vars.image.filename)}
    set_dict = {"links" : links_dict}
    upload_dict = {"upload" : set_dict}

    return dumps(upload_dict)

 

 

Note : in nicedit_image_upload controller, you should resize the images to avoid large images which will break your page layout.

You need to have PIL installed on your machine, and you just add the following code before links_dict = {"original":URL('static', 'images/pages_content/'+page_id+'/'+request.vars.image.filename)}

#Make a thumbnail (max 600*600px) of the uploaded Image
    try:
        from PIL import Image
        im = Image.open(pathfilename)
        im.thumbnail((600,600),Image.ANTIALIAS)
        im.save(pathfilename)
    except:
        pass

 

Related slices

Comments (1)

  • Login to post



  • 0
    titogarrido 6 years ago

    Heey nice slice!

     

    I couldn't see how it will work for new pages (without args). For new pages there is no page id yet, where will be placed the image file?

    replies (2)

Hosting graciously provided by:
Python Anywhere