Commits

Osiloke Emoekpere committed 98a5758

cleanup and fixes

Comments (0)

Files changed (6)

widget/defaults.py

     default=[
         "TestWidget"
     ],
+)
+
+register_setting(
+    name="WIDGET_PERMISSION_HANDLER",
+    label="Widget Permission Handler",
+    description=_("A class which handles permissions for widgets"),
+    editable=False,
+    default=None,
 )
 class WidgetForm(forms.ModelForm):
 
     def __init__(self, *args, **kwargs):
-        print kwargs
-        user = kwargs.get("initial").get("user")
-        if user.is_superuser:
-            restrict_list = None
-        else:
-            restrict_list = kwargs.pop("restrict_list", settings.RESTRICTED_WIDGETS)
+        restrict_list = kwargs.pop("restrict_list", settings.RESTRICTED_WIDGETS)
         super(WidgetForm, self).__init__(*args, **kwargs)
-        print self.data
+        try:
+            user = self.initial["user"]
+            if user.is_superuser:
+                restrict_list = None
+        except KeyError:
+            pass
+
         self.uuid = str(uuid4())
         self.fields["page"].queryset = Page.objects.get_query_set()
         self.fields["widget_class"].choices = get_all_page_widgets(restrict_list)
 
-
     class Meta:
         model = Widget
         fields = ('widget_class', 'user', 'page', 'widgetslot')

widget/templatetags/widget_tags.py

-
-from classytags.core import  Options, Tag
+from classytags.core import Options, Tag
 from classytags.helpers import InclusionTag
-from classytags.arguments import Argument, KeywordArgument
+from classytags.arguments import Argument, KeywordArgument, MultiKeywordArgument
 
 from django import template
 from django.core.urlresolvers import reverse
 
 from widget.models import Widget
 from widget.utilities import can
-from widget.widget_renderer import render_widgets_for_slot
-from widget.forms import  WidgetForm
+from widget.widget_renderer import render_widgets_for_slot, make_or_get_widget_for_slot
+from widget.forms import WidgetForm
 
 register = template.Library()
 
 
+class PlaceWidget(InclusionTag):
+    template = "widget/single_holder.html"
+    name = 'place_widget'
+    options = Options(
+        Argument('slot', required=True, resolve=False),
+        MultiKeywordArgument('kwargs', required=True, resolve=False),
+    )
+
+    def get_context(self, context, slot, kwargs):
+        page = context.get('page', None)
+
+        context['slot'] = slot
+        user = context['request'].user
+
+        rendered = make_or_get_widget_for_slot(slot, context, **kwargs)
+        if rendered:
+            context['widget'] = rendered
+            context['contains_widget'] = True
+        else:
+            context['contains_widget'] = False
+
+        return context
+
+
+register.tag(PlaceWidget)
+
+
 class RenderWidgets(InclusionTag):
     template = "widget/holder.html"
     name = 'render_widgets'
             context['widgets'] = rendered
             context['contains_widgets'] = True
         else:
-            context['widgets'] = [{'widget':Widget()}]
+            context['widgets'] = [{'widget': Widget()}]
             context['contains_widgets'] = False
-        #add widget list form for adding new widgets
-        form = WidgetForm(initial={"page":page,
-                                   "user":user,
-                                   "widgetslot":slot})
+            #add widget list form for adding new widgets
+        form = WidgetForm(initial={"page": page,
+                                   "user": user,
+                                   "widgetslot": slot})
         context['widget_form'] = form
 
         return context
 
+
 register.tag(RenderWidgets)
 
 
     options = Options(
         Argument('widget', required=True, resolve=True),
     )
+
     def get_context(self, widget):
         "create initial options"
         return '<a href="#" id="%s" rel="#edit-widget-form">Edit</a>' % (widget.id)
     try:
         page = context['page']
         user = context['request'].user
-        context.update({"widget_form": WidgetForm(initial={"page":page, "user":user})})
+        context.update({"widget_form": WidgetForm(initial={"page": page, "user": user})})
     except Exception:
         pass
     return context

widget/utilities.py

     def _dec(view):
         def _view(request, *args, **kwargs):
             data = view(request, *args, **kwargs)
-            print data
+            # print data
             return HttpResponse(json_serializer.encode(data),\
                     mimetype='application/json')
         _view.__name__ = view.__name__
 from mezzanine.utils.views import is_editable
 from mezzanine.core.models import CONTENT_STATUS_PUBLISHED, CONTENT_STATUS_DRAFT
 
-from widget.utilities import  LazyEncoder, ajax_view, get_model_form_for_widget, hasModel, get_widget_model_queryset
+from widget.utilities import LazyEncoder, ajax_view, get_model_form_for_widget, hasModel, get_widget_model_queryset
 from widget.forms import WidgetForm, WidgetOptionsForm
-from widget.widget_pool import  get_widget, WidgetHasNoOptions
+from widget.widget_pool import get_widget, WidgetHasNoOptions
 from widget.utilities import admin_can
 from widget.models import Widget
 from widget.utilities import ajaxerror
 
 json_serializer = LazyEncoder()
 
+
 @login_required
 @admin_can(Widget, action="change", fail404=True)
 def edit_widget(request, **kwargs):
         if request.POST:
             "get form populated with widget options"
             options_form = WidgetOptionsForm(widget.widget_class, \
-                                request.POST)
+                                             request.POST)
             if options_form.is_valid():
                 if options_form.save(widget=widget):
                     data = {'valid': True, 'form': 'saved'}
             if containsModel:
                 obj = get_widget_model_queryset(widget, widget_class_obj)
                 model_form = get_model_form_for_widget(widget_class_obj, \
-                        {"POST":request.POST, "FILES":request.FILES}, instance=obj, widget=widget)
+                                                       {"POST": request.POST, "FILES": request.FILES}, instance=obj,
+                                                       widget=widget)
                 try:
                     if model_form.is_valid():
-                        saved_obj=model_form.save()
+                        saved_obj = model_form.save()
                         data.update({"obj": saved_obj.id})
                     elif model_form.errors:
                         model_data = ajaxerror(model_form)
                         errors = dict(data.get("errors", {}), **model_data["errors"])
-                        data = {'valid': False, "errors": errors }
+                        data = {'valid': False, "errors": errors}
                 except Exception:
                     raise
         else:
             initial = {'status': widget.status}
             if widget.hasOptions:
                 initial.update(dict(("option_%s" % option.name, option.value) \
-                             for option in widget.options.all()))
+                                    for option in widget.options.all()))
             options_form = WidgetOptionsForm(widget.widget_class, \
-                            data=initial)
+                                             data=initial)
             extra_js = []
             o = get_template("widget/options.html")
             ctx.update({'options_form': options_form})
         extra_js = []
         o = get_template("widget/options.html")
         ctx.update({'options_form': options_form,
-                    'widget_class': widget_class_obj })
+                    'widget_class': widget_class_obj})
         model_form = get_model_form_for_widget(widget_class_obj)
         if model_form:
             ctx.update({'model_form': model_form})
 
         options = o.render(ctx)
         extra_js += options_form.extra_js
-        data = {'valid': False, 'type':'fi', 'data':options, 'extra_js': extra_js}
+        data = {'valid': False, 'type': 'fi', 'data': options, 'extra_js': extra_js}
     else:
         data = ajaxerror(widget_form)
     return HttpResponse(json_serializer.encode(data), mimetype='application/json')
+
+
 create_widget = require_POST(widget_list)
 
 
         elif options_form.errors:
             data = ajaxerror(options_form)
 
-
         if widget is None and not options_form.hasOptions and containsModel:
             try:
                 "update widget if it exists"
                 widget = Widget.objects.get(id=request.POST["widget"])
             except Exception:
                 widget = Widget(widgetslot=slot,
-                    widget_class=widget_class,
-                    user=request.user, page=page)
+                                widget_class=widget_class,
+                                user=request.user, page=page)
                 widget.save()
 
-
         model_widget = None
         if widget: model_widget = widget
         model_form = get_model_form_for_widget(widget_class_obj,
-            {"POST": request.POST, "FILES": request.FILES},
-            widget=model_widget
+                                               {"POST": request.POST, "FILES": request.FILES},
+                                               widget=model_widget
         )
         if model_form:
             try:
                 if model_form.is_valid():
-                    saved_obj=model_form.save()
+                    saved_obj = model_form.save()
                     data.update({"obj": saved_obj.id})
                 elif model_form.errors:
                     model_data = ajaxerror(model_form)
                     errors = dict(data.get("errors", {}), **model_data["errors"])
-                    data = {'valid': False, "errors": errors }
+                    data = {'valid': False, "errors": errors}
             except Exception:
                 raise
     except Exception, e:
         data = {"valid": False, \
-                "errors": { "_all_": ["Something went wrong, please refresh the page"], "exception": e.message}}
+                "errors": {"_all_": ["Something went wrong, please refresh the page"], "exception": e.message}}
     if "valid" in data and data["valid"]:
         return HttpResponse(json_serializer.encode(data), mimetype='application/json')
     return HttpResponseBadRequest(json_serializer.encode(data), mimetype='application/json')
+
+
 create_widget = require_POST(create_widget)
 
 
 @login_required
 @admin_can(Widget, action="delete")
 def delete_widget(request, id):
-
     data = {'valid': False}
     try:
         obj = Widget.objects.get(id=id)
         data = {'valid': True}
     except Exception:
         pass
-    return HttpResponse(json_serializer.encode(data),\
-        mimetype='application/json')
+    return HttpResponse(json_serializer.encode(data), \
+                        mimetype='application/json')
+
 
 @login_required
 @ajax_view()
         ctx = RequestContext(request)
         o = get_template("widget/options.html")
         ctx.update({'options_form': options_form,
-                    'widget_class': options_form.widget_class })
+                    'widget_class': options_form.widget_class})
 
         options = o.render(ctx)
         data = {'valid': True, 'type': 'fi', 'opts': options}
 
     return data
 
+
 @login_required
 @admin_can(Widget)
 def create_success(request):
                 try:
                     Widget.objects.filter(id=get_id(widget)).update(_order=i)
                 except Exception, e:
-                    data = {'status':False, 'error':str(e)}
+                    data = {'status': False, 'error': str(e)}
     try:
         moved_widget = int(get_id(request.POST.get("moved_widget", "")))
     except ValueError, e:
             widget.widgetslot = moved_parent
             widget.save()
         except Exception, e:
-            data = {'status':False, 'error':str(e)}
-    return HttpResponse(json_serializer.encode(data),\
-        mimetype='application/json')
+            data = {'status': False, 'error': str(e)}
+    return HttpResponse(json_serializer.encode(data), \
+                        mimetype='application/json')
 
 
 @login_required
         else:
             widget.status = CONTENT_STATUS_DRAFT
         widget.save()
-        data = {"status":True, "published": widget.status}
+        data = {"status": True, "published": widget.status}
     except Exception, e:
-        data = {"status":False, "error": str(e.message)}
+        data = {"status": False, "error": str(e.message)}
 
-    return HttpResponse(json_serializer.encode(data),\
-        mimetype='application/json')
+    return HttpResponse(json_serializer.encode(data), \
+                        mimetype='application/json')
 

widget/widget_renderer.py

             rendered = template.render(context)
     return rendered
 
+def make_or_get_widget_for_slot(slot, widget_context, widget_class, **kwargs):
+    """
+    Create or get a widget for a WidgetSlot
+    Useful when creating templates and you want to add, for example, a default slidshow widget
+
+    It only creates a new widget with the
+    """
+    page = widget_context.get("page", None)
+    user = widget_context["request"].user
+
+    widget_obj, created = Widget.objects.get_or_create(widgetslot=slot,
+        page=page, user=user, widget_class=widget_class).defaults(**kwargs)
+
+    return render_widget(widget_obj, widget_context)
+
+def render_widget(widget, widget_context):
+    """
+    Render a single widgtet
+    """
+    widget_class = get_widget(widget.widget_class)
+    widget_context.update({'widget': widget})
+
+    if widget_class is not None:
+        widget_options = None
+        widget_class = widget_class()
+        if hasattr(widget_class, "options"):
+            try:
+                widget_options = dict(((o["name"], o["value"])\
+                    for o in widget.options.values("name", "value")))
+                widget_context.update({"opts": widget_options})
+            except Exception, e:
+                raise e
+        queryset = get_widget_model_queryset(widget, widget_class)
+        rendered_widget = render_template(widget_class\
+        ._render(widget_context, widget.slot, queryset, widget_options),\
+            widget_class.template, raw=widget_class.raw)
+
+
+        return {'widget': widget,\
+                                 'meta': widget_class.Meta,\
+                                 'content': rendered_widget}
 
 def render_widgets_for_slot(slot, widget_context):
     """