Beispiel #1
0
class CommodityWizardForm(BaseFormMixin, models.ModelForm):
    product_name = fields.CharField(
        label=_("Product Name"), widget=widgets.TextInput(attrs={'size': 50}))
    slug = fields.CharField(label=_("Slug"),
                            widget=widgets.TextInput(attrs={'size': 50}))
    caption = HTMLFormField(label=_("Caption"), required=False)

    class Meta:
        model = Commodity
        fields = (
            'product_name',
            'slug',
            'caption',
            'product_code',
            'unit_price',
            'active',
            'show_breadcrumb',
            'sample_image',
        )

    @property
    def media(self):
        minimized = '' if settings.DEBUG else '.min'
        media = super().media
        css = {'all': ['admin/css/base.css', 'admin/css/forms.css']}
        media.add_css(css)
        media._js = [
            'admin/js/core.js',
            'admin/js/vendor/jquery/jquery{}.js'.format(minimized),
            'admin/js/jquery.init.js',
            'admin/js/urlify.js',
            'admin/js/prepopulate{}.js'.format(minimized),
        ] + media._js
        media.add_js([
            'filer/js/libs/mediator.min.js',
            'filer/js/libs/jquery.cookie.min.js',
            'filer/js/libs/fileuploader.min.js',
            'admin/js/admin/RelatedObjectLookups.js',
        ])
        return media

    def save(self, commit=True):
        self.instance.product_name = self.cleaned_data['product_name']
        self.instance.caption = self.cleaned_data['caption']
        self.instance.slug = self.cleaned_data['slug']
        max_order = Commodity.objects.aggregate(max=Max('order'))['max']
        self.instance.order = max_order + 1 if max_order else 1
        commodity = super().save(commit)
        ProductPageModel.objects.create(product=commodity,
                                        page=self.page.get_public_object())
        return commodity
 def test_html_form_field(self):
     html_field = HTMLFormField()
     self.assertTrue(isinstance(html_field.clean('some text'), SafeData))
Beispiel #3
0
class MarkerForm(ModelForm):
    title = CharField(
        label=_("Marker Title"),
        widget=widgets.TextInput(attrs={'size': 60}),
        help_text=_(
            "Please choose a title, then go to the map to set a marker pin"))

    use_icon = BooleanField(
        label=_("Use customized marker icon"),
        initial=False,
        required=False,
    )

    marker_image = ModelChoiceField(
        queryset=Image.objects.all(),
        label=_("Marker Image"),
        required=False,
    )

    marker_width = GlossaryFormField(
        widget=CascadingSizeWidget(allowed_units=['px'], required=False),
        label=_("Marker Width"),
        required=False,
        help_text=_("Width of the marker icon in pixels."),
    )

    marker_anchor = GlossaryFormField(
        widget=MultipleCascadingSizeWidget(['left', 'top'],
                                           allowed_units=['px', '%'],
                                           required=False),
        required=False,
        label=_("Marker Anchor"),
        help_text=
        _("The coordinates of the icon's anchor (relative to its top left corner)."
          ),
    )

    popup_text = HTMLFormField(
        required=False,
        help_text=_("Optional rich text to display in popup."),
    )

    position = Field(widget=widgets.HiddenInput)

    glossary_field_order = [
        'title', 'marker_width', 'marker_anchor', 'popup_text'
    ]

    class Meta:
        exclude = ['glossary']

    def __init__(self, *args, **kwargs):
        try:
            initial = dict(kwargs['instance'].glossary)
            has_original = True
        except (KeyError, AttributeError):
            initial = {}
            has_original = False
        initial.update(kwargs.pop('initial', {}))
        self.base_fields['position'].initial = json.dumps(
            initial.pop('position', {}))
        for key in self.glossary_field_order:
            self.base_fields[key].initial = initial.get(key)
        try:
            self.base_fields['marker_image'].initial = initial['image']['pk']
        except KeyError:
            self.base_fields['marker_image'].initial = None
            self.base_fields['use_icon'].initial = False
        else:
            self.base_fields['use_icon'].initial = True
        self.base_fields['marker_image'].widget = AdminFileWidget(
            ManyToOneRel(FilerImageField, Image, 'file_ptr'), site)
        super(MarkerForm, self).__init__(*args, **kwargs)
        if has_original:
            self.fields['title'].help_text = None

    def clean(self):
        try:
            position = self.cleaned_data['position']
            if isinstance(position, six.string_types):
                position = json.loads(position)
            elif not isinstance(position, dict):
                raise ValueError
        except (ValueError, KeyError):
            raise ValidationError(
                "Invalid internal position data. Check your Javascript imports."
            )
        else:
            if 'lat' not in position or 'lng' not in position:
                # place the marker in the center of the current map
                position = {
                    k: v
                    for k, v in self.instance.cascade_element.
                    glossary['map_position'].items() if k in ['lat', 'lng']
                }
            self.instance.glossary.update(position=position)

        marker_image = self.cleaned_data.pop('marker_image', None)
        if marker_image:
            image_data = {'pk': marker_image.pk, 'model': 'filer.Image'}
            self.instance.glossary.update(image=image_data)
        else:
            self.instance.glossary.pop('image', None)

        popup_text = self.cleaned_data.pop('popup_text', None)
        if strip_tags(popup_text):
            popup_text = strip_spaces_between_tags(popup_text)
            self.cleaned_data.update(popup_text=popup_text)

        for key in self.glossary_field_order:
            self.instance.glossary.update({key: self.cleaned_data.get(key)})
Beispiel #4
0
class MarkerForm(EntangledModelForm):
    title = CharField(
        label=_("Marker Title"),
        widget=widgets.TextInput(attrs={'size': 60}),
        help_text=_(
            "Please choose a title, then go to the map to set a marker pin"))

    use_icon = BooleanField(
        label=_("Use customized marker icon"),
        initial=False,
        required=False,
    )

    marker_image = AdminImageFormField(
        ManyToOneRel(FilerImageField, Image, 'file_ptr'),
        Image.objects.all(),
        label=_("Marker Image"),
        required=False,
        to_field_name='image_file',
    )

    marker_width = SizeField(
        label=_("Marker Width"),
        allowed_units=['px'],
        required=False,
        help_text=_("Width of the marker icon in pixels."),
    )

    marker_anchor = MultiSizeField(
        ['left', 'top'],
        label=_("Marker Anchor"),
        allowed_units=['px', '%'],
        required=False,
        help_text=
        _("The coordinates of the icon's anchor (relative to its top left corner)."
          ),
    )

    popup_text = HTMLFormField(
        required=False,
        help_text=_("Optional rich text to display in popup."),
    )

    position = HiddenDictField()

    class Meta:
        entangled_fields = {
            'glossary': [
                'title', 'use_icon', 'marker_image', 'marker_width',
                'marker_anchor', 'popup_text', 'position'
            ]
        }

    def clean(self):
        cleaned_data = super().clean()
        try:
            position = cleaned_data['position']
            if isinstance(position, str):
                position = json.loads(position)
            elif not isinstance(position, dict):
                raise ValueError
        except (ValueError, KeyError):
            raise ValidationError(
                "Invalid internal position data. Check your Javascript imports."
            )
        else:
            if 'lat' not in position or 'lng' not in position:
                # place the marker in the center of the current map
                position = {
                    k: v
                    for k, v in self.instance.cascade_element.
                    glossary['map_position'].items() if k in ['lat', 'lng']
                }
                cleaned_data['position'] = position

        popup_text = cleaned_data.pop('popup_text', '')
        if strip_tags(popup_text):
            cleaned_data['popup_text'] = strip_spaces_between_tags(popup_text)
        return cleaned_data
Beispiel #5
0
class SimpleTextForm(forms.Form):
    text = HTMLFormField()
Beispiel #6
0
class ArticleCreateForm(ArticleForm):
    content = HTMLFormField(label=_('Text'),
                            help_text=_('Initial content of the article.'),
                            required=False)
 def test_html_form_field(self):
     html_field = HTMLFormField()
     self.assertTrue(isinstance(html_field.clean('some text'), SafeData))