Exemplo n.º 1
0
    def __init__(self,
                 model,
                 limit_choices_to=None,
                 admin_site=None,
                 attrs=None,
                 using=None):
        """
        Instantiate the class.
        """
        if django.VERSION >= (1, 6, 0):
            rel = ManyToOneRel(None,
                               model,
                               model._meta.pk.name,
                               limit_choices_to=limit_choices_to)
        else:
            rel = ManyToOneRel(model,
                               model._meta.pk.name,
                               limit_choices_to=limit_choices_to)

        if django.VERSION < (1, 4):
            super(SimpleRawIdWidget, self).__init__(rel=rel,
                                                    attrs=attrs,
                                                    using=using)
        else:
            # admin_site was added in Django 1.4, fixing the popup URL for the change list.
            # Also default to admin.site, allowing a more auto-configuration style.
            if admin_site is None:
                admin_site = admin.site
            super(SimpleRawIdWidget, self).__init__(rel=rel,
                                                    admin_site=admin_site,
                                                    attrs=attrs,
                                                    using=using)
Exemplo n.º 2
0
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None):

        super(EquipamentoAdminForm, self).__init__(data, files, auto_id, prefix, initial,
                                                   error_class, label_suffix, empty_permitted, instance)

        # Configurando a relação entre Equipamento e Entidade para aparecer o botão de +
        # O self.admin_site foi declarado no admin.py
        if django.VERSION[0:2] >= (1, 6):
            rel = ManyToOneRel(field=Equipamento._meta.get_field('entidade_fabricante'), to=Entidade, field_name='id')  # @UndefinedVariable
        else:
            rel = ManyToOneRel(Entidade, 'id')

        self.fields['entidade_fabricante'].widget = RelatedFieldWidgetWrapper(self.fields['entidade_fabricante'].widget,
                                                                              rel, self.admin_site)
Exemplo n.º 3
0
 def __init__(self, *args, **kwargs):
     super(ImageFormMixin, self).__init__(*args, **kwargs)
     try:
         self.fields['image_file'].initial = kwargs['instance'].image.pk
     except (AttributeError, KeyError):
         pass
     self.fields['image_file'].widget = AdminFileWidget(ManyToOneRel(FilerImageField, Image, 'file_ptr'), site)
Exemplo n.º 4
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)
Exemplo n.º 5
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)
Exemplo n.º 6
0
 def __init__(self, *args, **kwargs):
     model_name_tuple = filer_settings.FILER_IMAGE_MODEL.split('.')
     Image = apps.get_model(*model_name_tuple, require_ready=False)
     kwargs.setdefault('label', _("Image"))
     super().__init__(
         ManyToOneRel(FilerImageField, Image, 'file_ptr'),
         Image.objects.all(),
         'image_file', *args, **kwargs)
Exemplo n.º 7
0
 def __init__(self, *args, **kwargs):
     super(AdminActionForm, self).__init__(*args, **kwargs)
     try:
         entity_model = self.instance.content_type.model_class()
     except:
         entity_model = Org
     self.fields['entity_id'].widget = ForeignKeyRawIdWidget(
         rel=ManyToOneRel(entity_model, 'id'))
Exemplo n.º 8
0
 def __init__(self, *args, **kwargs):
     try:
         self.base_fields['image_file'].initial = kwargs['initial'][
             'image']['pk']
     except KeyError:
         self.base_fields['image_file'].initial = None
     self.base_fields['image_file'].widget = AdminFileWidget(
         ManyToOneRel(FilerImageField, Image, 'file_ptr'), site)
     super(ImageFormMixin, self).__init__(*args, **kwargs)
Exemplo n.º 9
0
 def __init__(self, *args, **kwargs):
     super(find_slum, self).__init__(*args, **kwargs)
     self.fields['slumname'] = forms.ModelChoiceField(
         queryset=Slum.objects.all(),
         widget=ForeignKeyRawIdWidget(rel=ManyToOneRel(
             Slum._meta.get_field('id'), Slum, 'id'),
                                      admin_site=admin.site))
     self.fields['slumname'].widget.attrs.update(
         {'class': 'customized-form'})
     self.fields['slumname'].label = "Select slum"
Exemplo n.º 10
0
 def __init__(self, *args, **kwargs):
     try:
         initial = dict(kwargs['instance'].glossary)
     except (KeyError, AttributeError):
         initial = {}
     initial.update(kwargs.pop('initial', {}))
     for key in self.glossary_fields:
         self.base_fields[key].initial = initial.get(key)
     try:
         self.base_fields['image_file'].initial = initial['image']['pk']
     except KeyError:
         self.base_fields['image_file'].initial = None
     self.base_fields['image_file'].widget = AdminFileWidget(ManyToOneRel(FilerImageField, Image, 'file_ptr'), site)
     super(GalleryImageForm, self).__init__(*args, **kwargs)
Exemplo n.º 11
0
 def __init__(self, *args, **kwargs):
     super(account_find_slum, self).__init__(*args, **kwargs)
     self.fields['account_slumname'] = forms.ModelChoiceField(
         queryset=Slum.objects.all(),
         widget=ForeignKeyRawIdWidget(rel=ManyToOneRel(
             Slum._meta.get_field('id'), Slum, 'id'),
                                      admin_site=admin.site))
     self.fields['account_cityname'] = forms.ModelChoiceField(
         queryset=City.objects.all())
     self.fields['account_slumname'].widget.attrs.update(
         {'class': 'customized-form'})
     self.fields['account_slumname'].widget.attrs.update({
         'name':
         'account_slumname',
         'id':
         'id_account_slumname'
     })
     self.fields['account_slumname'].label = "Select slum"
     self.fields['account_cityname'].widget.attrs.update(
         {'class': 'customized-form'})
     self.fields['account_cityname'].widget.attrs.update({
         'name':
         'account_cityname',
         'id':
         'account_cityname'
     })
     self.fields['account_cityname'].label = "Select city"
     self.fields['account_start_date'] = forms.DateField(
         widget=AdminTimeWidget())
     self.fields['account_start_date'].label = "From"
     self.fields['account_start_date'].widget.attrs.update({
         'name':
         'account_start_date',
         'class':
         'datepicker',
         'style':
         'width:80px;'
     })
     self.fields['account_end_date'] = forms.DateField(
         widget=AdminTimeWidget())  #extras.SelectDateWidget())
     self.fields['account_end_date'].label = "To"
     self.fields['account_end_date'].widget.attrs.update({
         'name':
         'account_end_date',
         'class':
         'datepicker',
         'style':
         'width:80px;'
     })
Exemplo n.º 12
0
 def __init__(self, *args, **kwargs):
     super(GenericRelationForm, self).__init__(*args, **kwargs)
     try:
         model = self.instance.content_type.model_class()
         model_key = model._meta.pk.name
     except Exception:
         model = self._meta.model
         model_key = 'id'
     self.fields['object_id'].widget = ForeignKeyRawIdWidget(
         rel=ManyToOneRel('object_id', model, model_key),
         admin_site=admin.site
     )
     self.fields['content_type'].widget.widget = ContentTypeSelect(
         'lookup_id_object_id',
         self.fields['content_type'].widget.widget.attrs,
         self.fields['content_type'].widget.widget.choices)
Exemplo n.º 13
0
 def form_field (self, etype, initial=None):
   if etype == 'image':
     return forms.ModelChoiceField(
       queryset=Image.objects.all(),
       required=False, label='Content',
       widget=ForeignKeyRawIdWidget(ManyToOneRel(Image, 'id'), admin.site),
       initial=initial
     )
     
   elif etype == 'rich':
     return forms.CharField(required=False, label='Content', widget=RichText, initial=initial)
     
   elif etype == 'plain':
     return forms.CharField(required=False, label='Content', widget=forms.Textarea, initial=initial)
     
   return forms.CharField(max_length=255, required=False, label='Content', initial=initial, widget=forms.TextInput(attrs={'class': 'vTextField'}))
Exemplo n.º 14
0
 def form_field (self, etype, name, initial=None, req=False):
   field = models.ForeignKey(Image, blank=True, null=True)
   
   if etype == 'image':
     return forms.ModelChoiceField(
       queryset=Image.objects.all(),
       required=req, label=name,
       widget=ForeignKeyRawIdWidget(ManyToOneRel(field, Image, 'id', related_name='+'), admin.site),
       initial=initial
     )
     
   elif etype == 'rich':
     return forms.CharField(required=req, label=name, widget=RichText, initial=initial)
     
   elif etype == 'plain':
     return forms.CharField(required=req, label=name, widget=forms.Textarea, initial=initial)
     
   return forms.CharField(max_length=255, required=req, label=name, initial=initial, widget=forms.TextInput(attrs={'class': 'vTextField'}))
Exemplo n.º 15
0
 def __init__(self,
              model,
              limit_choices_to=None,
              admin_site=None,
              attrs=None,
              using=None):
     """
     Instantiate the class.
     """
     if admin_site is None:
         admin_site = admin.site
     rel = ManyToOneRel(None,
                        model,
                        model._meta.pk.name,
                        limit_choices_to=limit_choices_to)
     super(SimpleRawIdWidget, self).__init__(rel=rel,
                                             admin_site=admin_site,
                                             attrs=attrs,
                                             using=using)
Exemplo n.º 16
0
    def __init__(self, *args, **kwargs):
        super(One2ManyModelForm, self).__init__(*args, **kwargs)
        admin_site = getattr(self, 'admin_site', admin.site)

        for field in self.related_one2manyfields:
            related_model = field.related_model
            related_name = field.name
            fake_manytoone_rel = ManyToOneRel(field, related_model,
                                              related_model._meta.pk.name)

            try:
                self.fields[related_name].initial = getattr(
                    self.instance, related_name, None)
            except Exception:
                pass

            self.fields[related_name].widget = RelatedFieldWidgetWrapper(
                self.fields[related_name].widget,
                fake_manytoone_rel,
                admin_site,
                can_change_related=True)
Exemplo n.º 17
0
class ImageFormMixin(EntangledModelFormMixin):
    image_file = AdminImageFormField(
        ManyToOneRel(FilerImageField, Image, 'file_ptr'),
        Image.objects.all(),
        to_field_name='image_file',
        label=_("Image"),
    )

    image_title = CharField(
        label=_('Image Title'),
        required=False,
        help_text=_("Caption text added to the 'title' attribute of the <img> element."),
    )

    alt_tag = CharField(
        label=_('Alternative Description'),
        required=False,
        help_text=_("Textual description of the image added to the 'alt' tag of the <img> element."),
    )

    _image_properties = EntangledField()

    class Meta:
        entangled_fields = {'glossary': ['image_file', 'image_title', 'alt_tag', '_image_properties']}

    def clean(self):
        cleaned_data = super().clean()
        image_file = cleaned_data.get('image_file')
        if not image_file:
            raise ValidationError(_("No image has been selected."))
        # _image_properties are just a cached representation, maybe useless
        cleaned_data['_image_properties'] = {
            'width': image_file._width,
            'height': image_file._height,
            'exif_orientation': image_file.exif.get('Orientation', 1),
        }
        return cleaned_data
Exemplo n.º 18
0
 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
Exemplo n.º 19
0
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None):

        if instance:
            if initial:
                initial.update({'equipamento': instance.equipamento})
            else:
                initial = {'equipamento': instance.equipamento}

            initial.update({'patrimonio': instance.patrimonio})
            initial.update({'form_filhos': [(p.id, p.apelido, p.ns, p.descricao)
                                            for p in Patrimonio.objects.filter(patrimonio=instance)]})
            if instance.pagamento_id:
                initial.update({'termo': instance.pagamento.protocolo.termo})

        super(PatrimonioAdminForm, self).__init__(data, files, auto_id, prefix, initial,
                                                  error_class, label_suffix, empty_permitted, instance)

        pg = self.fields['pagamento']
        if data and 'termo' in data and data['termo']:
            t = data['termo']
            t = Termo.objects.get(id=t)
            pg.queryset = Pagamento.objects.filter(protocolo__termo=t)
        elif instance and instance.pagamento:
            pg.choices = [(p.id, p.__unicode__()) for p in Pagamento.objects.filter(id=instance.pagamento.id)]
        else:
            pg.queryset = Pagamento.objects.filter(id__lte=0)

        pt = self.fields['patrimonio']
        if data and 'patrimonio' in data and data['patrimonio']:
            pt.choices = [(p.id, p.__unicode__()) for p in Patrimonio.objects.filter(id=data['patrimonio'])]
        elif instance and instance.patrimonio:
            pt.choices = [(p.id, p.__unicode__()) for p in Patrimonio.objects.filter(id=instance.patrimonio.id)]
        else:
            pt.queryset = Patrimonio.objects.filter(id__lte=0)

        # Configurando a relação entre Patrimonio e Equipamento para aparecer o botão de +
        # O self.admin_site foi declarado no admin.py
        if django.VERSION[0:2] >= (1, 6):
            rel = ManyToOneRel(field=Patrimonio._meta.get_field('equipamento'), to=Equipamento, field_name='id')  # @UndefinedVariable
        else:
            rel = ManyToOneRel(Equipamento, 'id')

        self.fields['equipamento'].widget = RelatedFieldWidgetWrapper(self.fields['equipamento'].widget, rel,
                                                                      self.admin_site)

        # Configurando a relação entre Equipamento e Entidade para aparecer o botão de +
        # O self.admin_site foi declarado no admin.py
        if django.VERSION[0:2] >= (1, 6):
            rel = ManyToOneRel(field=Patrimonio._meta.get_field('entidade_procedencia'), to=Entidade, field_name='id')  # @UndefinedVariable
        else:
            rel = ManyToOneRel(Entidade, 'id')

        procedencia_field = self.fields['entidade_procedencia']
        procedencia_field.widget = RelatedFieldWidgetWrapper(procedencia_field.widget, rel, self.admin_site)

        """
        et = self.fields['entidade_procedencia']
        if data and data['entidade_procedencia']:
            t = data['entidade_procedencia']
            et.queryset = Entidade.objects.filter(pk=t)
        elif instance and instance.entidade_procedencia:
            et.choices = [(p.id, p.__unicode__()) for p in Entidade.objects.filter(id=instance.entidade_procedencia.id)]
        else:
            # ************ROGERIO: MODIFICAR PARA UM FILTRO POR ATRIBUTO/ FLAG
            #entidadeHistoricoList = EntidadeHistorico.objects.filter(tipo__nome= 'Fabricante')
            .values_list('entidade_id', flat=True)
            #et.queryset = Entidade.objects.filter(id__in=entidadeHistoricoList)
            et.queryset = Entidade.objects.all()
        """
        # Exibe a quantidade de patrimonios filhos no label
        self.fields['form_filhos'].label = u'Patrimônios contidos (%s)' % \
                                           Patrimonio.objects.filter(patrimonio=instance).count()

        filtro_widget = self.fields['filtro_equipamento'].widget
        if instance:
            if instance.equipamento:
                filtro_widget = forms.TextInput(attrs={'onkeydown': 'if (event.keyCode == 13) {$(\'#id_equipamento\')'
                                                                    '.focus(); return false;}',
                                                       'onchange': 'ajax_filter_equipamento(this.value, "%s", "%s");' %
                                                                   (instance.id, instance.equipamento.id)})
            else:
                filtro_widget = forms.TextInput(attrs={'onkeydown': 'if (event.keyCode == 13) {$(\'#id_equipamento\')'
                                                                    '.focus(); return false;}',
                                                       'onchange': 'ajax_filter_equipamento(this.value, "%s");' %
                                                                   instance.id})
        else:
            filtro_widget = forms.TextInput(attrs={'onkeydown': 'if (event.keyCode == 13) {$(\'#id_equipamento\')'
                                                                '.focus(); return false;}',
                                                   'onchange': 'ajax_filter_equipamento(this.value, "");'})
Exemplo n.º 20
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
Exemplo n.º 21
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
Exemplo n.º 22
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