Source

django-cloudi / widgets.py

Full commit
from django import forms
from django.utils.safestring import mark_safe


class CloudImages(forms.TextInput):
    '''
       You must create symlink in your media folder
       so the js and css can be served.
       ln -s fancybox path/to/django-cloudi/fancybox 
    '''
    class Media:
        js = (
             'fancybox/jquery.fancybox-1.3.4.pack.js',
            )
        css = {
            'screen': ('fancybox/jquery.fancybox-1.3.4.css',),
            }


    def __init__(self, attrs=None):
        ''' Updates the field that has been assigned the widget 
            with the class="cloudimages" attribute  '''
        self.attrs = {'class': 'cloudimages'}
        if attrs:
            self.attrs.update(attrs)
        super(CloudImages, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        rendered = super(CloudImages, self).render(name, value, attrs)
        return rendered + mark_safe(u'''<script type="text/javascript">
            /* Declaring global so it can be passed between functions. */
            var Cloudiurl = ''; 
            $(document).ready(function () {
                /* Add the link to upload after the input box. */
                $('#id_%s').after("<a class='cloudimages' style='margin:0em 1em;font-size:14px;' href='/cloud/'>Upload Image</a>");
                /* Bind fancybox to the class as an iframe. Once the file upload
                   is complete get the image link and add it to the form field */
                $('.cloudimages').fancybox({
                'autoScale'         : false,
                'transitionIn'      : 'none',
                'transitionOut'     : 'none',
                'type'              : 'iframe',
                 onCleanup          : function () {
                     /* Server returns the url & this function gets the
                        url from the page text */
                     Cloudiurl = $('iframe#fancybox-frame').contents().text();           
                      },
                 onClosed           : function () {
                     /* When the form is close the url var is returned */
                     $('#id_%s').val(Cloudiurl);
                                            }
                 });

            });                        
            </script>''' % (name, name))