Esempio n. 1
0
    def render(self, name, value, attrs=None):
        file_widget = AdminFileWidget(DummyForeignObjectRel(), site)
        file_widget = file_widget.render('file', None, {'id': 'id_file'})
        file_widget = re.sub(r'<script.*?>.*?</script>', r'', file_widget, flags=re.DOTALL)

        context = {
            'value': value,
            'file_widget': file_widget,
            'filer_api': reverse('content_api'),
            'reserved_vars': json.dumps(settings.RESERVED_VARIABLES)
        }

        html = render_to_string('admin/content_widget.html', context)
        return mark_safe(html)
Esempio n. 2
0
    def __init__(self, data=None, *args, **kwargs):
        instance = kwargs.get('instance')
        default_link_type = {'type': self.LINK_TYPE_CHOICES[0][0]}
        initial = dict(instance.glossary) if instance else {
            'link': default_link_type
        }
        initial.update(kwargs.pop('initial', {}))
        initial.setdefault('link', {'type': default_link_type})
        link_type = initial['link']['type']
        self.base_fields['link_type'].choices = self.LINK_TYPE_CHOICES
        self.base_fields['link_type'].initial = link_type
        if data and data.get('shared_glossary'):
            # convert this into an optional field since it is disabled with ``shared_glossary`` set
            self.base_fields['link_type'].required = False
        set_initial_linktype = getattr(self,
                                       'set_initial_{}'.format(link_type),
                                       None)
        if 'django_select2' not in settings.INSTALLED_APPS:
            # populate classic Select field for choosing a CMS page
            site = get_current_site()
            choices = [(p.pk,
                        format_page_link(p.get_page_title(),
                                         p.get_absolute_url()))
                       for p in Page.objects.drafts().on_site(site)]
            self.base_fields['cms_page'].choices = choices

        if callable(set_initial_linktype):
            set_initial_linktype(initial)
        self._preset_section(data, initial)
        self.base_fields['download_file'].widget = AdminFileWidget(
            ManyToOneRel(FilerFileField, FilerFileModel, 'id'), admin_site)
        super(LinkForm, self).__init__(data, initial=initial, *args, **kwargs)
Esempio n. 3
0
 def __init__(self,
              queryset=FilerImageModel.objects.all(),
              widget=AdminFileWidget(
                  ManyToOneRel(FilerImageField, FilerImageModel, 'id'),
                  admin_site),
              *args,
              **kwargs):
     super().__init__(queryset=queryset, widget=widget, *args, **kwargs)
Esempio n. 4
0
class VideoPlayerForm(BasePlayerForm):
    file = PlusModelChoiceField(label=_("Video File"),
                                queryset=FilerFileModel.objects.all(),
                                widget=AdminFileWidget(
                                    ManyToOneRel(FilerFileField,
                                                 FilerFileModel, 'id'),
                                    admin_site),
                                required=True,
                                validators=[validate_video_file],
                                help_text=_("Video file for the player"))

    poster = PlusModelChoiceField(
        label=_("Video Thumbnail"),
        queryset=FilerFileModel.objects.all(),
        widget=AdminFileWidget(
            ManyToOneRel(FilerFileField, FilerFileModel, 'id'), admin_site),
        required=False,
        help_text=_("Thumbnail on stopped video file "),
    )
Esempio n. 5
0
class AudioPlayerForm(BasePlayerForm):
    file = PlusModelChoiceField(
        label=_("Audio File"),
        queryset=FilerFileModel.objects.all(),
        widget=AdminFileWidget(
            ManyToOneRel(FilerFileField, FilerFileModel, 'id'), admin_site),
        required=True,
        validators=[validate_audio_file],
        help_text=_("Audio file for the player"),
    )
Esempio n. 6
0
class LinkForm(EntangledModelFormMixin):
    LINK_TYPE_CHOICES = [
        ('cmspage', _("CMS Page")),
        ('download', _("Download File")),
        ('exturl', _("External URL")),
        ('email', _("Mail To")),
    ]

    link_type = fields.ChoiceField(
        label=_("Link"),
        help_text=_("Type of link"),
    )

    cms_page = LinkSearchField(
        required=False,
        label='',
        help_text=_("An internal link onto any CMS page of this site"),
    )

    section = SectionChoiceField(
        required=False,
        label='',
        help_text=_("Page bookmark"),
    )

    download_file = ModelChoiceField(
        label='',
        queryset=FilerFileModel.objects.all(),
        widget=AdminFileWidget(ManyToOneRel(FilerFileField, FilerFileModel, 'id'), admin_site),
        required=False,
        help_text=_("An internal link onto a file from filer"),
    )

    ext_url = fields.URLField(
        required=False,
        label=_("URL"),
        help_text=_("Link onto external page"),
    )

    mail_to = fields.EmailField(
        required=False,
        label=_("Email"),
        help_text=_("Open Email program with this address"),
    )

    link_target = fields.ChoiceField(
        choices=[
            ('', _("Same Window")),
            ('_blank', _("New Window")),
            ('_parent', _("Parent Window")),
            ('_top', _("Topmost Frame")),
        ],
        label=_("Link Target"),
        widget=RadioSelect,
        required=False,
        help_text=_("Open Link in other target."),
    )

    link_title = fields.CharField(
        label=_("Title"),
        required=False,
        help_text=_("Link's Title"),
    )

    class Meta:
        entangled_fields = {'glossary': ['link_type', 'cms_page', 'section', 'download_file', 'ext_url', 'mail_to',
                                         'link_target', 'link_title']}

    def __init__(self, *args, **kwargs):
        link_type_choices = []
        if not getattr(self, 'require_link', True):
            link_type_choices.append(('', _("No Link")))
            self.declared_fields['link_type'].required = False
        link_type_choices.extend(self.LINK_TYPE_CHOICES)
        self.declared_fields['link_type'].choices = link_type_choices
        self.declared_fields['link_type'].initial = link_type_choices[0][0]
        instance = kwargs.get('instance')
        if instance and instance.glossary.get('link_type') == 'cmspage':
            self._preset_section(instance)
        super().__init__(*args, **kwargs)

    def _preset_section(self, instance):
        """
        Field ``cms_page`` may refer onto any CMS page, which itself may contain bookmarks. This method
        creates the list of bookmarks.
        """
        self.base_fields['section'].choices = self.base_fields['section'].choices[:1]
        try:
            cascade_page = get_related_object(instance.glossary, 'cms_page').cascadepage
            for key, val in cascade_page.glossary.get('element_ids', {}).items():
                self.base_fields['section'].choices.append((key, val))
        except (AttributeError, ObjectDoesNotExist):
            pass

    def clean(self):
        cleaned_data = super().clean()
        link_type = cleaned_data.get('link_type')
        error = None
        if link_type == 'cmspage':
            if cleaned_data['cms_page'] is None:
                error = ValidationError(_("CMS page to link to is missing."))
                self.add_error('cms_page', error)
        elif link_type == 'download':
            if cleaned_data['download_file'] is None:
                error = ValidationError(_("File for download is missing."))
                self.add_error('download_file', error)
        elif link_type == 'exturl':
            ext_url = cleaned_data['ext_url']
            if ext_url:
                try:
                    response = requests.head(ext_url, allow_redirects=True)
                    if response.status_code != 200:
                        error = ValidationError(_("No external page found on {url}.").format(url=ext_url))
                except Exception as exc:
                    error = ValidationError(_("Failed to connect to {url}.").format(url=ext_url))
            else:
                error = ValidationError(_("No external URL provided."))
            if error:
                self.add_error('ext_url', error)
        elif link_type == 'email':
            mail_to = cleaned_data['mail_to']
            if not re.match(r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)', mail_to):
                error = ValidationError(_("'{email}' is not a valid email address.").format(email=mail_to))
                self.add_error('mail_to', error)
        if error:
            raise error
        return cleaned_data

    @classmethod
    def unset_required_for(cls, sharable_fields):
        """
        Fields borrowed by `SharedGlossaryAdmin` to build its temporary change form, only are
        required if they are declared in `sharable_fields`. Otherwise just deactivate them.
        """
        if 'link_content' in cls.base_fields and 'link_content' not in sharable_fields:
            cls.base_fields['link_content'].required = False
        if 'link_type' in cls.base_fields and 'link' not in sharable_fields:
            cls.base_fields['link_type'].required = False
Esempio n. 7
0
class LinkForm(EntangledModelFormMixin):
    LINK_TYPE_CHOICES = [
        ('cmspage', _("CMS Page")),
        ('download', _("Download File")),
        ('exturl', _("External URL")),
        ('email', _("Mail To")),
    ]
    if PhoneNumberField:
        LINK_TYPE_CHOICES.append(('phonenumber', _("Phone number")))

    link_type = fields.ChoiceField(
        label=_("Link"),
        help_text=_("Type of link"),
    )

    cms_page = LinkSearchField(
        required=False,
        label='',
        help_text=_("An internal link onto any CMS page of this site"),
    )

    section = SectionChoiceField(
        required=False,
        label='',
        help_text=_("Page bookmark"),
    )

    download_file = ModelChoiceField(
        label='',
        queryset=FilerFileModel.objects.all(),
        widget=AdminFileWidget(ManyToOneRel(FilerFileField, FilerFileModel, 'id'), admin_site),
        required=False,
        help_text=_("An internal link onto a file from filer"),
    )

    ext_url = fields.URLField(
        required=False,
        label=_("URL"),
        help_text=_("Link onto external page"),
    )

    mail_to = fields.EmailField(
        required=False,
        label=_("Email"),
        help_text=_("Open Email program with this address"),
    )

    if PhoneNumberField:
        phone_number = PhoneNumberField(
            required=False,
            label=_("Phone Number"),
            help_text=_("International phone number, ex. +1 212 555 2368."),
        )

    link_target = fields.ChoiceField(
        choices=[
            ('', _("Same Window")),
            ('_blank', _("New Window")),
            ('_parent', _("Parent Window")),
            ('_top', _("Topmost Frame")),
        ],
        label=_("Link Target"),
        widget=RadioSelect,
        required=False,
        help_text=_("Open Link in other target."),
    )

    link_title = fields.CharField(
        label=_("Title"),
        required=False,
        help_text=_("Link's Title"),
    )

    class Meta:
        entangled_fields = {'glossary': ['link_type', 'cms_page', 'section', 'download_file', 'ext_url', 'mail_to',
                                         'link_target', 'link_title']}
        if PhoneNumberField:
            entangled_fields['glossary'].append('phone_number')

    def __init__(self, *args, **kwargs):
        link_type_choices = []
        if not getattr(self, 'require_link', True):
            link_type_choices.append(('', _("No Link")))
            self.declared_fields['link_type'].required = False
        link_type_choices.extend(self.LINK_TYPE_CHOICES)
        self.declared_fields['link_type'].choices = link_type_choices
        self.declared_fields['link_type'].initial = link_type_choices[0][0]
        instance = kwargs.get('instance')
        if instance and instance.glossary.get('link_type') == 'cmspage':
            self._preset_section(instance)
        super().__init__(*args, **kwargs)

    def _preset_section(self, instance):
        """
        Field ``cms_page`` may refer onto any CMS page, which itself may contain bookmarks. This method
        creates the list of bookmarks.
        """
        self.base_fields['section'].choices = self.base_fields['section'].choices[:1]
        try:
            cascade_page = get_related_object(instance.glossary, 'cms_page').cascadepage
            for key, val in cascade_page.glossary.get('element_ids', {}).items():
                self.base_fields['section'].choices.append((key, val))
        except (AttributeError, ObjectDoesNotExist):
            pass

    def _post_clean(self):
        super()._post_clean()
        empty_fields = [None, '']
        link_type = self.cleaned_data['glossary'].get('link_type')
        if link_type == 'cmspage':
            if self.cleaned_data['glossary'].get('cms_page', False) in empty_fields:
                error = ValidationError(_("CMS page to link to is missing."), code='required')
                self.add_error('cms_page', error)
        elif link_type == 'download':
            if self.cleaned_data['glossary'].get('download_file', False) in empty_fields:
                error = ValidationError(_("File for download is missing."), code='required')
                self.add_error('download_file', error)
        elif link_type == 'exturl':
            ext_url = self.cleaned_data['glossary'].get('ext_url', False)
            if ext_url in empty_fields:
                error = ValidationError(_("No valid URL provided."), code='required')
                self.add_error('ext_url', error)
        elif link_type == 'email':
            if self.cleaned_data['glossary'].get('mail_to', False) in empty_fields:
                error = ValidationError(_("No email address provided."), code='required')
                self.add_error('mail_to', error)
        elif link_type == 'phonenumber':
            if self.cleaned_data['glossary'].get('phone_number', False) in empty_fields:
                error = ValidationError(_("No phone number provided."), code='required')
                self.add_error('phone_number', error)

    def clean_phone_number(self):
        return str(self.cleaned_data['phone_number'])

    @classmethod
    def unset_required_for(cls, sharable_fields):
        """
        Fields borrowed by `SharedGlossaryAdmin` to build its temporary change form, only are
        required if they are declared in `sharable_fields`. Otherwise just deactivate them.
        """
        if 'link_content' in cls.base_fields and 'link_content' not in sharable_fields:
            cls.base_fields['link_content'].required = False
        if 'link_type' in cls.base_fields and 'link' not in sharable_fields:
            cls.base_fields['link_type'].required = False