Commits

Osiloke Emoekpere  committed 781c017

Cleaned up the source a bit

  • Participants
  • Parent commits bcf6692
  • Branches enhancements

Comments (0)

Files changed (12)

File docs/page-widgets.rst

+****************************************************
+Creating Page Widgets
+****************************************************
+
+=============
+Basic Widgets
+=============
+
+================
+Advanced Widgets
+================

File example/settings.py

     "mezzanine.core.middleware.TemplateForDeviceMiddleware",
     "mezzanine.core.middleware.DeviceAwareFetchFromCacheMiddleware",
     "mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware",
+    "mezzanine.pages.middleware.PageMiddleware",
     # Uncomment the following if using any of the SSL settings:
     # "mezzanine.core.middleware.SSLRedirectMiddleware",
 )

File example/widgets/fixtures/initial_data.json

-[{"pk": 2, "model": "blog.blogpost", "fields": {"status": 2, "allow_comments": false, "description": "Wow, blogging is great!", "title": "Another Blogy", "rating_average": 0.0, "categories": [], "site": 1, "keywords_string": "", "content": "Wow, blogging is great!", "rating_count": 0, "comments_count": 0, "user": 1, "featured_image": null, "short_url": null, "publish_date": "2012-03-04 19:02:31", "slug": "another-blogy", "expiry_date": null}}, {"pk": 1, "model": "blog.blogpost", "fields": {"status": 2, "allow_comments": false, "description": "I want to blog", "title": "First Blogy", "rating_average": 0.0, "categories": [], "site": 1, "keywords_string": "", "content": "I want to blog", "rating_count": 0, "comments_count": 0, "user": 1, "featured_image": null, "short_url": null, "publish_date": "2012-03-04 18:54:29", "slug": "first-blogy", "expiry_date": null}}, {"pk": 1, "model": "widget.widget", "fields": {"status": 2, "expiry_date": null, "acts_on": "", "_order": 0, "author": "Progweb Team", "widgetslot": "main", "display_title": "Social Logos", "widget_class": "sociallogoswidget", "site": 1, "widget_file_title": "", "publish_date": "2012-03-03 14:59:47", "user": 1, "active": true, "page": 8, "page_less": false}}, {"pk": 5, "model": "widget.widget", "fields": {"status": 2, "expiry_date": null, "acts_on": "", "_order": 1, "author": "Progweb Team", "widgetslot": "right", "display_title": "bloglistwidget_3", "widget_class": "bloglistwidget", "site": 1, "widget_file_title": "", "publish_date": "2012-03-04 18:56:55", "user": 1, "active": true, "page": null, "page_less": true}}, {"pk": 6, "model": "widget.widget", "fields": {"status": 2, "expiry_date": null, "acts_on": "", "_order": 2, "author": "Progweb Team", "widgetslot": "right", "display_title": "twittermentionswidgets_3", "widget_class": "twittermentionswidgets", "site": 1, "widget_file_title": "", "publish_date": "2012-03-04 19:29:10", "user": 1, "active": true, "page": null, "page_less": true}}, {"pk": 1, "model": "widget.widgetoptionentry", "fields": {"widget": 6, "name": "Tag", "value": "#mezzanine"}}, {"pk": 2, "model": "widget.widgetoptionentry", "fields": {"widget": 6, "name": "Limit", "value": "5"}}]

File widget/defaults.py

+from mezzanine.conf import register_setting
+
+from django.utils.translation import ugettext as _
+
+#register_setting(
+#    name="IMAGE_FIELD_WIDGET_CLASS",
+#    description=_("Dotted package path and class name of the widget to use "
+#                  "for the image fields`."),
+#    editable=False,
+#    default="django.forms.FileInput",
+#)

File widget/forms.py

-from datetime import datetime
-from os.path import join
-
 from django import forms
 from django.forms.widgets import HiddenInput
-from mezzanine.core.models import CONTENT_STATUS_CHOICES, CONTENT_STATUS_DRAFT
 
 from widget.widget_pool import get_widget_options, WidgetHasNoOptions
 from widget.models import WidgetOptionEntry, Widget
 
 from mezzanine.pages.models import Page
-import option_fields as fields
+import option_fields
 
-from easyweb.apps.core import widget_fields
 from mezzanine.conf import settings
 from uuid import uuid4
 
 
-#def get_widget_form()
 class WidgetForm(forms.ModelForm):
 
     def __init__(self, *args, **kwargs):
     """
     extra_js = []
     hasOptions = False
-#    status = forms.ChoiceField(choices=CONTENT_STATUS_CHOICES, initial=CONTENT_STATUS_DRAFT)
 
     def __init__(self, widget_class, *args, **kwargs):
         """
             self.hasOptions = True
             for field in self.form_fields:
                 field_key = "option_%s" % field.name
-                field_class = fields.CLASSES[field.field_type]
-                field_widget = fields.WIDGETS.get(field.field_type)
+                field_class = option_fields.CLASSES[field.field_type]
+                field_widget = option_fields.WIDGETS.get(field.field_type)
                 field_args = {"label": field.name, "required": field.required,
                               "help_text": field.help_text}
                 arg_names = field_class.__init__.im_func.func_code.co_varnames
                 if field.required:
                     css_class += " required"
                     if (settings.FORMS_USE_HTML5 and
-                        field.field_type != fields.CHECKBOX_MULTIPLE):
+                        field.field_type != option_fields.CHECKBOX_MULTIPLE):
                         field_key_widget.attrs["required"] = ""
                 try:
                     field_key_widget.attrs["class"] = css_class + " " + field_key_widget.attrs["class"]
         """
         Save all option ``WidgetOptionEntry`` with reference to the passed widget.
         """
-#        widget.status = self.cleaned_data['status']
-#        widget.save()
 
         if self.hasOptions:
             for field in self.form_fields:
 
 
 def ModelFormForWidget(widget_model, fields=None, widget=None):
-    meta_data = { "model":widget_model, }
-    #Left over from mezzanine
+    meta_data = { "model": widget_model, }
+
     try:
         widget_overrides = settings.WIDGET_OVERRIDES
     except AttributeError:
     meta = type('Meta', (), meta_data)
 
     class WidgetModelForm(forms.ModelForm):
+        extra_js = []
+
         def __init__(self, *args, **kwargs):
             super(WidgetModelForm, self).__init__(*args, **kwargs)
             self.uuid = str(uuid4())
             for f in self.fields.keys():
-#                'Make page model content type id a hidden field'
-#                if parent_model == f: self.fields[f].widget = forms.HiddenInput()
-#                if f in hidden_fields: self.fields[f].widget = forms.HiddenInput()
                 field_class = self.fields[f].__class__
                 try:
                     field_type = widget_overrides[field_class]
                 except KeyError:
                     pass
                 else:
-                    self.fields[f].widget = widget_fields.WIDGETS[field_type]()
+                    self.fields[f].widget = option_fields.WIDGETS[field_type]()
                 css_class = self.fields[f].widget.attrs.get("class", "")
                 css_class += " " + field_class.__name__.lower()
                 self.fields[f].widget.attrs["class"] = css_class
                 self.fields[f].widget.attrs["id"] = "%s" % (f)
 
+                try:
+                    self.extra_js.append("this.%s('%s');" % (self.fields[f].widget.META.init_js, "%s" % f))
+                except Exception:
+                    pass
+
     modelform_class = type('modelform', (WidgetModelForm,), {"Meta": meta})
     return modelform_class

File widget/models.py

 from mezzanine.core.managers import PublishedManager, SearchableManager, CurrentSiteManager
 from mezzanine.core.models import Orderable, Displayable, \
     CONTENT_STATUS_CHOICES, CONTENT_STATUS_DRAFT, Ownable, SiteRelated
-from easyweb.utilities.admin import reversion_models
+
 from .option_fields import TEXT
 from mezzanine.pages.models import Page
 
     value = models.CharField(max_length=settings.FORMS_FIELD_MAX_LENGTH)
 
     def __unicode__(self):
-        return '' or self.name
+        return '' or '%s [%s]' % (self.name, self.value)
 
     class Meta:
         verbose_name = _("Widget Option entry")

File widget/option_fields.py

 
 from django import forms
 from django.forms.extras import SelectDateWidget
-from django.utils.importlib import import_module
+
 from django.utils.translation import ugettext_lazy as _
 
 from mezzanine.conf import settings
 URL = 14
 RICHTEXTAREA = 15
 IMAGE = 16
+
 # Names for all available field types.
 NAMES = (
     (TEXT, _("Single line text")),
     DATE: SelectDateWidget,
     DATE_TIME: SplitSelectDateTimeWidget,
     HIDDEN: forms.HiddenInput,
+    IMAGE: forms.FileInput
     }
 
+#tiny hack to use IMAGE WIDGET CLASS if it exists
+try:
+    WIDGETS.update({IMAGE: import_dotted_path(settings.IMAGE_FIELD_WIDGET_CLASS)})
+except AttributeError:
+    pass
+
 # Some helper groupings of field types.
 CHOICES = (CHECKBOX, CHECKBOX_MULTIPLE, SELECT,
            SELECT_MULTIPLE, RADIO_MULTIPLE)

File widget/page_widgets.py

-from widget import widget_pool
 from widget.models import WidgetOption as opt, WidgetClassBase
 
 from django.utils.translation import ugettext_lazy as _
     raw = True
     default_placeholder = "test"
     options = [
-        opt(name="Option 1"),
-        opt(name="Option 2"),
-        opt(name="Option 3")
+        opt(name="First"),
+        opt(name="Second"),
+        opt(name="Third")
     ]
 
-    def render(self, context, slot, queryset, **kwargs):
+    def render(self, context, slot, queryset=None, options=None, **kwargs):
         return context
 
     class Meta:
         name = _("Test")
         author = 'Osiloke Emoekpere'
 
-#widget_pool.register_widget(TestWidget)

File widget/templates/widget/widget_loader.html

 
 <link rel="stylesheet" href="{{ STATIC_URL }}widget/css/widget.css">
 {% include "widget/widget_form.html" %}
-{% include "widget/edit_widget_form.html" %}
 {% endif %}

File widget/tests.py

 """
 import pdb
 from django.contrib.auth.models import User
+from django.template import RequestContext, Context
 from django.test import TestCase
 
 from mezzanine.core.models import CONTENT_STATUS_DRAFT
 from mezzanine.pages.models import RichTextPage
+from widget import widget_pool
 
 from widget.forms import WidgetOptionsForm
 from widget.models import Widget
-from widget.widget_pool import get_widget
+from widget.page_widgets import TestWidget
+from widget.widget_pool import get_widget, WidgetAlreadyRegistered
 from widget.widget_renderer import render_widgets_for_slot
 
 
         self._user = User.objects.create_superuser(username=self._username, \
                         password=self._password, email="example@example.com")
 
+        #register our test widget
+        try:
+            widget_pool.register_widget(TestWidget)
+        except WidgetAlreadyRegistered:
+            pass
+
+        #create page with widget slots
+        self.page = RichTextPage.objects.create(title="testpage",
+            status=CONTENT_STATUS_DRAFT)
+        #create widget slot :)
+        self.slot = "slot"
+
+        #create test widget
+        self.test_widget = Widget()
+        self.test_widget.widget_class = 'TestWidget'
+        self.test_widget.page = self.page
+        self.test_widget.user_id = 1
+        self.test_widget.widgetslot = self.slot
+        self.test_widget.save()
+
     def test_widget_creation(self):
-        test_widget = Widget()
-        test_widget.widget_class = 'TestWidget'
-        test_widget.user_id = 1
-        widget_class = get_widget(test_widget.widget_class)
-
+        widget_class = get_widget(self.test_widget.widget_class)
         self.assertEqual(widget_class.Meta.name, "Test")
 
-    def test_widget_options_form(self):
+    def test_widget_options_form_creation(self):
 
         form = WidgetOptionsForm("TestWidget")
         field_label = [f for f in form.fields]
-        expected = ['name', 'option_Option 1',\
-                 'option_Option 2', 'option_Option 3']
+        expected = ['option_First',\
+                 'option_Second', 'option_Third']
 
-        self.assertEqual(field_label, expected)
+        self.assertListEqual(field_label, expected)
 
     def test_widget_options_form_saving(self):
-        pass
+        """
+        This will create a new test widget with the assigned options
+        """
+        form = WidgetOptionsForm("TestWidget",
+            data={"option_First":"Option 1", "option_Second":"Option 2", "option_Third":"Option 3"}
+        )
+        self.assertEqual(form.is_valid(), True)
 
-    def test_widget_renderer(self):
-        #create page with widget slots
-        page = RichTextPage.objects.create(title="testpage",
-                                           status=CONTENT_STATUS_DRAFT)
-        #create widget slot
-        slot = "slot" 
+        form.save(self.test_widget)
 
-        #create test widget
-        test_widget = Widget()
-        test_widget.widget_class = 'TestWidget'
-        test_widget.page = page
-        test_widget.user_id = 1
-        test_widget.slot = slot
-        test_widget.save()
+        self.assertListEqual([o.value for o in self.test_widget.options.all()], ['Option 1', 'Option 2', 'Option 3'])
 
+    def test_widget_renderer_for_page(self):
+
+        #mock context
         context = {}
-        context["page"] = page
-        context["request"] = {"user": self._user}
+        context["page"] = self.page
+
+        #mock request
+        request = type('request', (object,), {'user':self._user})
+        context["request"] = request
+
         #render widget, there should be only one widget i.e test_widget
-        widgets = render_widgets_for_slot(slot, context)
-        self.assertEqual(widgets[0]['widget'], test_widget)
+        #This returns all widget's in the mentioned slot
+
+        widgets = render_widgets_for_slot(self.slot, Context(context))
+
+        self.assertEqual(widgets[0]['widget'], self.test_widget)
         #check if rendered content is correct
         self.assertEqual(widgets[0]['content'], "Test Widget Rendered")
+

File widget/views.py

                              for option in widget.options.all()))
             options_form = WidgetOptionsForm(widget.widget_class, \
                             data=initial)
-
+            extra_js = []
             o = get_template("widget/options.html")
             ctx.update({'options_form': options_form})
             if containsModel:
                 model_form = get_model_form_for_widget(widget_class_obj, instance=obj, widget=widget)
                 if model_form:
                     ctx.update({'model_form': model_form})
+                    extra_js += model_form.extra_js
 
             options = o.render(ctx)
 
-            extra_js = options_form.extra_js
+            extra_js += options_form.extra_js
             data = {'valid': False, 'type': 'ef', 'data': options, 'extra_js': extra_js}
 
         return HttpResponse(json_serializer.encode(data), \
             "Widget has options, lets generate the options form"
             options_form = WidgetOptionsForm(widget_class)
             if widget_form.is_valid():
+                extra_js = []
                 o = get_template("widget/options.html")
                 ctx.update({'options_form': options_form,
                             'widget_class': widget_class_obj })
                 model_form = get_model_form_for_widget(widget_class_obj)
                 if model_form:
                     ctx.update({'model_form': model_form})
+                    extra_js += model_form.extra_js
 
                 options = o.render(ctx)
-                data = {'valid': False, 'type':'fi', 'data':options}
+                extra_js += options_form.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')
             slot = request.POST["widgetslot"]
             try:
                 page = Page.objects.get(id=request.POST["page"])
-                print page
+
                 ### HANDLE OPTIONS FORM ####
                 options_form = WidgetOptionsForm(widget_class, request.POST, request.FILES)
                 widget = None

File widget/widget_renderer.py

-
+import os
 from widget.models import  Widget
 from widget.utilities import get_widget_model_queryset
 from widget.widget_pool import get_widget
     """
     rendered = ''
     if raw:
-        template = get_template_from_string(template)
-        template.name = "custom_template"
-        rendered = template.render(context)
+        template_object = get_template_from_string(template, name="custom_template_" + os.urandom(32))
+        rendered = template_object.render(context)
     else:
         if isinstance(template, str):
             rendered = render_to_string(template, context)
             queryset = get_widget_model_queryset(widget, widget_class)
             rendered_widget = render_template(widget_class\
                     ._render(widget_context, slot, queryset, widget_options),\
-                              widget_class.template, widget_class.raw)
+                              widget_class.template, raw=widget_class.raw)
 
 
             rendered_widgets.append({'widget': widget, \