Пример #1
0
 def __init__(self, request, *args, **kwargs):
     self.next_view = kwargs.pop('next_view', None)
     super(CreateApplicationCredentialForm,
           self).__init__(request, *args, **kwargs)
     role_list = self.request.user.roles
     role_names = [role['name'] for role in role_list]
     role_choices = ((name, name) for name in role_names)
     self.fields['roles'].choices = role_choices
     keystone_version = api.keystone.get_identity_api_version(request)
     if keystone_version < (3, 13):
         del self.fields['access_rules']
     if not settings.KUBECONFIG_ENABLED:
         self.fields['kubernetes_namespace'].widget = widgets.HiddenInput()
Пример #2
0
 def __init__(self, *args, **kwargs):
     try:
         self.default_order_field = self.model._meta.ordering[0]
     except IndexError:
         self.default_order_field = self.model.Meta.ordering[0]
     except AttributeError:
         msg = "Model {0}.{1} requires a list or tuple 'ordering' in its Meta class".format(
             self.model.__module__, self.model.__name__)
         raise ImproperlyConfigured(msg)
     self.form.base_fields[self.default_order_field].is_hidden = True
     self.form.base_fields[self.default_order_field].required = False
     self.form.base_fields[
         self.default_order_field].widget = widgets.HiddenInput()
     super(CustomInlineFormSet, self).__init__(*args, **kwargs)
Пример #3
0
    def __init__(self, *args, **kwargs):
        self.default_order_direction, self.default_order_field = _get_default_ordering(
            self.model, self)

        if self.default_order_field not in self.form.base_fields:
            self.form.base_fields[self.default_order_field] = \
                self.model._meta.get_field(self.default_order_field).formfield()

        self.form.base_fields[self.default_order_field].is_hidden = True
        self.form.base_fields[self.default_order_field].required = False
        self.form.base_fields[
            self.default_order_field].widget = widgets.HiddenInput()

        super().__init__(*args, **kwargs)
Пример #4
0
    def __init__(self, *args, **kwargs):
        # Set the job request
        self.job_request = kwargs.pop('job_request')

        super(JobMatchingForm, self).__init__(*args, **kwargs)

        amount, currency = self.fields['client_pay_per_hour'].fields
        self.fields['client_pay_per_hour'].widget = \
            Bootstrap3SterlingMoneyWidget(
               amount_widget=amount.widget,
               currency_widget=widgets.HiddenInput(attrs={'value': 'GBP'}),
               attrs={'step': '0.25'})

        self.set_initial_based_on_job_request()
Пример #5
0
 class Meta:
     model = Product
     fields = ('product_name', 'product_wiki', 'product_manager',
               'product_contact', 'dev_manager', 'dev_contact',
               'qa_manager', 'qa_contact', 'safe_manager', 'safe_contact',
               'product_desc', 'id')
     exclude = None  #排除的字段
     labels = None  #提示信息
     help_texts = None  #帮助提示信息
     widgets = None  #自定义插件
     error_messages = None  #自定义错误信息
     widgets = {
         "product_name":
         wid.TextInput(attrs={
             'class': 'smallinput',
             'placeholder': "如:支付系统"
         }),
         "product_wiki":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "product_manager":
         wid.TextInput(attrs={
             'class': 'smallinput',
             'placeholder': "如:张启山"
         }),
         "product_contact":
         wid.TextInput(attrs={
             'class': 'smallinput',
             'placeholder': "如:[email protected]"
         }),
         "dev_manager":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "dev_contact":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "qa_manager":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "qa_contact":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "safe_manager":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "safe_contact":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "product_desc":
         wid.Textarea(attrs={
             'cols': 80,
             'rows': 5,
             'class': 'mediuminput'
         }),
         "id":
         wid.HiddenInput()
     }
Пример #6
0
class ReEstablishIdentityForm(DeclarationIdentityForm):
    email = NHSEmailField()
    gmc = forms.CharField(widget=widgets.HiddenInput())

    def clean(self):
        super(ReEstablishIdentityForm, self).clean()

        email, gmc = self.cleaned_data['email'], self.cleaned_data['gmc']
        doctor = Doctor.objects.get(gmc_number=gmc)
        if doctor.email != email:
            raise forms.ValidationError(
                'A different email address was used to submit declarations for that doctor in the past'
            )
        return self.cleaned_data
Пример #7
0
 def __init__(self, *args, **kwargs):
     try:
         initial = dict(kwargs['instance'].glossary)
     except (KeyError, AttributeError):
         initial = {}
     initial.update(kwargs.pop('initial', {}))
     try:
         self.base_fields['product'].initial = initial['product']['pk']
     except KeyError:
         self.base_fields['product'].initial = None
     if not is_installed('adminsortable2'):
         self.base_fields['order'].widget = widgets.HiddenInput()
         self.base_fields['order'].initial = 0
     super(ProductGalleryForm, self).__init__(*args, **kwargs)
Пример #8
0
class TextIconPlugin(IconPluginMixin, LinkPluginBase):
    """
    This plugin is intended to be used inside the django-CMS-CKEditor.
    """
    name = _("Icon in text")
    text_enabled = True
    render_template = 'cascade/plugins/texticon.html'
    ring_plugin = 'IconPlugin'
    parent_classes = ['TextPlugin']
    model_mixins = (TextIconModelMixin, LinkElementMixin,)
    allow_children = False
    require_parent = False

    icon_font = GlossaryField(
        widgets.Select(),
        label=_("Font"),
        initial=get_default_icon_font,
    )

    symbol = GlossaryField(
        widgets.HiddenInput(),
        label=_("Select Symbol"),
    )

    color = GlossaryField(
        ColorPickerWidget(),
        label=_("Icon color"),
    )

    glossary_field_order = ['icon_font', 'symbol', 'color']

    class Media:
        js = ['cascade/js/admin/iconplugin.js']

    @classmethod
    def requires_parent_plugin(cls, slot, page):
        return False

    def get_form(self, request, obj=None, **kwargs):
        kwargs.update(form=VoluntaryLinkForm.get_form_class())
        return super(TextIconPlugin, self).get_form(request, obj, **kwargs)

    @classmethod
    def get_inline_styles(cls, instance):
        inline_styles = cls.super(TextIconPlugin, cls).get_inline_styles(instance)
        color = instance.glossary.get('color')
        if isinstance(color, list) and len(color) == 2 and not color[0]:
            inline_styles['color'] = color[1]
        return inline_styles
Пример #9
0
class StockCountAmountForm(BootstrapModelForm):
    product_id = forms.IntegerField(widget=widgets.HiddenInput())

    def __init__(self, product=None, *args, **kwargs):
        super(StockCountAmountForm, self).__init__(*args, **kwargs)
        if product:
            self.fields['product_id'].initial = product.pk
            self.prod = product

    class Meta:
        model = StockProductAmount
        exclude = (
            'stockcount',
            'product',
        )
Пример #10
0
    def __init__(self, *args, **kwargs):
        super(PlaceRelationAdminForm, self).__init__(*args, **kwargs)
        # We're using a public API endpoint that hides the "real" pks
        # and instead exposes a UUID-based key.  We need to translate
        # between the UUID and the Django pk
        parent_pk = self.initial.get('parent', None)
        if parent_pk:
            parent_obj = Place.objects.get(pk=parent_pk)
            self.initial['parent'] = parent_obj.place_id

        if (hasattr(self.instance, 'child') and self.instance.child.geolevel):
            # This is a bound instance
            # Limit the queryset
            self.fields['parent'].queryset = Place.objects.filter(
                geolevel=self.instance.child.geolevel.parent)
            widget_style = self.fields['parent'].widget.attrs.get(
                'style', None)
            addl_styles = 'min-width: 200px;'
            widget_style = ("%s %s" % (widget_style, addl_styles)
                            if widget_style else addl_styles)
            self.fields['parent'].widget.attrs['style'] = widget_style

        else:
            # This is a new instance
            # Swap the selection widget out with a hidden input
            # (as required by Select2) and pass some parameters to
            # client-side JavaScript
            attrs = {
                'class':
                'select2-enable',
                'data-ajax-url':
                reverse("api_dispatch_list",
                        kwargs={
                            'resource_name': 'places',
                            'api_name': '0.1'
                        }),
                'data-ajax-datatype':
                'json',
                'data-ajax-result-attr':
                'name',
                'data-ajax-selection-attr':
                'name',
                'data-ajax-filter-function':
                'geoLevelFilters',
                'style':
                'min-width: 200px;'
            }
            self.fields['parent'].widget = widgets.HiddenInput(attrs=attrs)
Пример #11
0
    class Meta():
        model = TestResult

        fields = {
            'title',
            'description',
            'released',
            'patient_ID',
            'comment',
        }

        widgets = {
            'title': widgets.TextInput(attrs={'class': 'form-control'}),
            'description': widgets.TextInput(attrs={'class': 'form-control'}),
            'patient_ID': widgets.HiddenInput(),
        }
Пример #12
0
 class Meta:
     model = Assets
     fields = ('assets_type', 'status', 'idc', 'cabinet_no',
               'cabinet_order', 'tags', 'id')
     exclude = None  #排除的字段
     labels = None  #提示信息
     help_texts = None  #帮助提示信息
     widgets = None  #自定义插件
     error_messages = None  #自定义错误信息
     # error_messages = {
     #     'name':{'required':"用户名不能为空",},
     #     'age':{'required':"年龄不能为空",},
     # }
     widgets = {
         "assets_type":
         wid.Select(choices=common.TYPE_VALUE),
         "status":
         wid.Select(choices=common.STATUS_VALUE),
         "idc":
         wid.TextInput(attrs={
             'class': 'smallinput',
             'placeholder': "如:10.24.22.12"
         }),
         "cabinet_no":
         wid.TextInput(attrs={
             'class': 'smallinput',
             'placeholder': "如:10.24.22.12"
         }),
         "cabinet_order":
         wid.TextInput(attrs={
             'class': 'smallinput',
             'placeholder': "如:10.24.22.12"
         }),
         "tags":
         wid.TextInput(attrs={
             'class': 'smallinput',
             'placeholder': "如:阿里云 高配"
         }),
         "id":
         wid.HiddenInput()
     }
     labels = {
         "idc": "IDC机房(可选)",
         "cabinet_no": "机柜号(可选)",
         "cabinet_order": "机柜中序号(可选)",
         "tags": "资产标签(可选)"
     }
Пример #13
0
class TrackUpdateFormAjax(forms.ModelForm):

    pk = forms.IntegerField(
        widget=widgets.HiddenInput()
    )

    class Meta:
        model = models.Track
        fields = [
            'name',
            'volume',
            'color',
            'audioset'
        ]
        widgets = {
            'audioset' : widgets.HiddenInput()
        }
Пример #14
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_field_order:
         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)
     if not is_installed('adminsortable2'):
         self.base_fields['order'].widget = widgets.HiddenInput()
         self.base_fields['order'].initial = 0
     super(GalleryImageForm, self).__init__(*args, **kwargs)
Пример #15
0
 def get_form(self, request, obj=None, **kwargs):
     """
     Hide owner field in group
     :param request:
     :param obj:
     :param kwargs:
     :return:
     """
     form = super(CustomGroupAdmin, self).get_form(request, obj, **kwargs)
     self.exclude = ('owner',)
     if 'owner' in form.base_fields:
         form.base_fields['owner'].widget = widgets.HiddenInput()
     # print(form.base_fields)
     if 'permissions' in form.base_fields:
         permissions = form.base_fields['permissions']
         permissions.queryset = get_users_permissions_list(request, permissions)
     return form
Пример #16
0
    def __init__(self, request=None, *args, **kwargs):
        if request is None:
            raise TypeError("Keyword argument 'request' must be supplied.")
        super(ReportForm, self).__init__(*args, **kwargs)
        QUARTER_START_CHOICES = (
            ('', '---'),
            ('01', 'January'),
            ('02', 'February'),
            ('03', 'March'),
            ('04', 'April'),
            ('05', 'May'),
            ('06', 'June'),
            ('07', 'July'),
            ('08', 'August'),
            ('09', 'September'),
            ('10', 'October'),
            ('11', 'November'),
            ('12', 'December'),
        )
        self.request = request
        orgs = UserProfile.objects.filter(user__exact=request.user)

        org_choices, prod_choices, user_choices, cats_choices = [], [], [], []
        for o in orgs:
            org_choices.append((o.org.id, o.org))
            users = UserProfile.objects.filter(org=o.org)
            cats = Category.objects.filter(org=o.org)
            prods = Product.objects.filter(categories__in=cats)
            for p in prods:
                prod_choices.append((p.id, p.name))
            for u in users:
                user_choices.append((u.id, "%s [%s]" % (u.user.get_full_name(), o.org)))
            for c in cats:
                cats_choices.append((c.id, "[%d] %s" % (c.id, c.name)))

        self.fields['orgs'].choices = org_choices
        self.fields['products'].choices = prod_choices
        self.fields['ordered_by'].choices = user_choices
        self.fields['categories'].choices = cats_choices
        self.fields['quarter_start'].widget = widgets.Select(choices=QUARTER_START_CHOICES)
        self.fields['start_date'].widget = widgets.TextInput(attrs={'class': 'datepicker', 'size': '12'})
        self.fields['end_date'].widget = widgets.TextInput(attrs={'class': 'datepicker', 'size': '12'})
        self.fields['last_orders'].widget = widgets.TextInput(attrs={'size': '3'})
        self.fields['scheduled'].widget = widgets.CheckboxInput()
        self.fields['schedule'].widget = widgets.HiddenInput()
        self.fields['states'].widget = widgets.SelectMultiple(choices=Order.STATUS_CHOICES)
Пример #17
0
 def handle_registrar_fields(form):
     if request.user.is_supported_by_registrar():
         registrars = set(org.registrar
                          for org in request.user.organizations.all())
         if len(registrars) > 1:
             form.fields['registrar'].choices = [
                 (registrar.id, registrar.name) for registrar in registrars
             ]
         if len(registrars) == 1:
             form.fields['registrar'].widget = widgets.HiddenInput()
             registrar = registrars.pop()
             form.fields['registrar'].initial = registrar.id
             form.fields['registrar'].choices = [(registrar.id,
                                                  registrar.email)]
     else:
         del form.fields['registrar']
     return form
Пример #18
0
 def __init__(self, *args, **kwargs):
     try:
         if self.model._meta.ordering[0].startswith('-'):
             self.default_order_field = self.model._meta.ordering[0][1:]
         else:
             self.default_order_field = self.model._meta.ordering[0]
     except IndexError:
         self.default_order_field = self.model.Meta.ordering[0]
     except AttributeError:
         msg = ("Model {0}.{1} requires a list or tuple 'ordering'"
                " in its Meta class".format(self.model.__module__,
                                            self.model.__name__))
         raise ImproperlyConfigured(msg)
     self.form.base_fields[self.default_order_field].is_hidden = True
     self.form.base_fields[self.default_order_field].required = False
     widget = widgets.HiddenInput(attrs={'class': 'default-order-field'})
     self.form.base_fields[self.default_order_field].widget = widget
     super(CustomInlineFormSet, self).__init__(*args, **kwargs)
Пример #19
0
class CommentForm(Form):
    content_type = fields.CharField(widget=widgets.HiddenInput)
    object_id = fields.IntegerField(widget=widgets.HiddenInput)
    text = fields.CharField(widget=CKEditorWidget(config_name='comment_ckeditor'),
                            error_messages={'required':'评论内容不能为空'})
    reply_comment_id = fields.IntegerField(widget=widgets.HiddenInput(attrs={'id':'reply_comment_id'}))

    def __init__(self,*args,**kwargs):
        if 'user' in kwargs:
            self.user = kwargs.pop('user')
        super(CommentForm,self).__init__(*args,**kwargs)

    def clean(self):
        # 判断用户是否登录
        if self.user.is_authenticated:
            self.cleaned_data['user'] = self.user
        else:
            raise ValidationError('用户尚未登录')

        # 评论对象验证
        content_type = self.cleaned_data['content_type']
        object_id = self.cleaned_data['object_id']
        try:
            model_class = ContentType.objects.get(model=content_type).model_class()
            model_obj = model_class.objects.get(pk=object_id)
            self.cleaned_data['content_object'] = model_obj
        except ObjectDoesNotExist:
            raise ValidationError('评论对象不存在')

        return self.cleaned_data

    def clean_reply_comment_id(self):
        reply_comment_id = self.cleaned_data['reply_comment_id']
        if reply_comment_id < 0:
            raise ValidationError('回复出错')
        elif reply_comment_id == 0:
            self.cleaned_data['parent'] = None
        elif Comment.objects.filter(pk=reply_comment_id).count():
            self.cleaned_data['parent'] = Comment.objects.get(pk=reply_comment_id)
        else:
            raise ValidationError('回复出错')
        return self.cleaned_data
Пример #20
0
 class Meta:
     model = StorageConfig
     fields = ('storage_type', 'server_ip', 'login_user', 'login_passwd',
               'login_port', 'install_status', 'server_user', 'server_path',
               'nfs_exports', 'storage_class', 'provisioner_name', 'id')
     exclude = None  #排除的字段
     labels = None  #提示信息
     help_texts = None  #帮助提示信息
     widgets = None  #自定义插件
     error_messages = None  #自定义错误信息
     widgets = {
         "storage_type":
         wid.Select(choices=common.STORAGE_TYPE,
                    attrs={'style': 'margin: 0px;height:30px'}),
         "server_ip":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "login_user":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "login_passwd":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "login_port":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "install_status":
         wid.Select(choices=common.COMMON_STATUS,
                    attrs={'style': 'margin: 0px;height:30px'}),
         "server_user":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "server_path":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "nfs_exports":
         wid.Textarea(attrs={
             'cols': 80,
             'rows': 5,
             'class': 'mediuminput'
         }),
         "storage_class":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "provisioner_name":
         wid.TextInput(attrs={'class': 'smallinput'}),
         "id":
         wid.HiddenInput(),
     }
Пример #21
0
class UpdateProgressForm(forms.Form):
    progress = forms.ModelChoiceField(
        queryset=BookProgress.objects.all(),
        widget=widgets.HiddenInput(),
    )
    current_page = forms.IntegerField(min_value=1)
    date = forms.DateField(initial=date.today())
    read_pages = forms.IntegerField(min_value=1)

    def save(self):
        progress = self.cleaned_data['progress']
        current_page = self.cleaned_data['current_page'] + self.cleaned_data[
            'read_pages']
        progress.page = min(current_page, progress.book.pages)
        progress.save(update_fields=['page'])
        progress.daily.update_or_create(
            date=self.cleaned_data['date'],
            defaults={'read_pages': self.cleaned_data['read_pages']},
        )
        return progress
Пример #22
0
class CommentForm(BaseEmptyForm):
    """
    A simple comment form
    """
    allow_creation = False
    allow_edition = False
    redirect_to = forms.CharField(widget=widgets.HiddenInput(), required=False)

    class Meta:
        from twistranet.content_types.models import Comment
        model = Comment
        fields = ('description', )
        widgets = {
            'description':
            widgets.Textarea(attrs={
                'class': 'comment-description-field',
                'cols': '',
                'rows': ''
            }),
        }
Пример #23
0
class ScheduleForm(forms.Form):
    """
    Form to provide for simple editing/commenting on an inbound progrssnote for PACT
    """

    #http://techblog.appnexus.com/2011/easy-web-forms-with-knockout-js/

    sunday = forms.ChoiceField(choices=[], required=False)
    monday = forms.ChoiceField(choices=[], required=False)
    tuesday = forms.ChoiceField(choices=[], required=False)
    wednesday = forms.ChoiceField(choices=[], required=False)
    thursday = forms.ChoiceField(choices=[], required=False)
    friday = forms.ChoiceField(choices=[], required=False)
    saturday = forms.ChoiceField(choices=[], required=False)

    comment = forms.CharField(required=False)
    active_date = forms.DateField(
        help_text=
        "Date this schedule should be made active.  Note active time is 12:01am the day you choose.",
        required=True,
        widget=widgets.TextInput(),
        initial=datetime.utcnow().strftime("%m/%d/%Y")
    )  #attrs={"value": datetime.utcnow().strftime("%m-%d-%Y")}))

    schedule_id = forms.CharField(widget=widgets.HiddenInput(),
                                  initial=make_uuid)

    @memoized
    def get_user_choices(self):
        users = CommCareUser.by_domain(PACT_DOMAIN)
        #        return [(x._id, x.raw_username) for x in users]
        yield (None, "-- unassigned --")
        for x in users:
            yield (x.raw_username, x.raw_username)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        user_choices = list(self.get_user_choices())
        for day in DAYS_OF_WEEK:
            self.fields[day].choices = user_choices
Пример #24
0
    class Meta:

        model = OpenHouses
        exclude = ['id']

        widgets = {
            'property':
            widgets.Select(attrs={'class': 'form-control'}),
            'user':
            widgets.HiddenInput(attrs={'class': 'form-control'}),
            'length':
            widgets.NumberInput(attrs={
                'class': 'form-control',
                'placeholder': 'Length in minutes'
            }),
            'time':
            widgets.DateTimeInput(attrs={
                'class': 'form-control',
                'placeholder': 'dd/mm/yyyy hh:mm'
            })
        }
Пример #25
0
class IconFormMixin(EntangledModelFormMixin):
    icon_font = ModelChoiceField(
        IconFont.objects.all(),
        label=_("Font"),
        initial=get_default_icon_font,
    )

    symbol = CharField(
        widget=widgets.HiddenInput(),
        label=_("Select Symbol"),
    )

    class Meta:
        entangled_fields = {'glossary': ['icon_font', 'symbol']}

    def __init__(self, *args, **kwargs):
        if not getattr(self, 'require_icon', True):
            self.declared_fields['icon_font'].required = False
            self.declared_fields['icon_font'].empty_label = _("No Icon")
            self.declared_fields['symbol'].required = False
        super().__init__(*args, **kwargs)
Пример #26
0
    def render(self, name, value, attrs=None):
        """
        Renders the widget HTML, placing the widgets in alphabetical order.
        """
        if value is not None and not isinstance(value, six.string_types):
            value = edit_string_for_tags(
                [o.tag for o in value.select_related("tag")])

        # Render the HTML of the widget
        tag_it_html = render_to_string(
            'taggit/widget.html', {
                'widget_name': name,
                'tag_list': value,
                'placeholder_text': self.placeholder_text
            })

        # Render the hidden input
        hidden_field = widgets.HiddenInput(attrs)

        # Return the safe HTML combining the custom widgget and the hidden input
        return mark_safe(u"{}{}".format(
            tag_it_html, hidden_field.render(name, value, attrs)))
Пример #27
0
class TextIconPlugin(IconPluginMixin, CascadePluginBase):
    name = _("Icon in text")
    text_enabled = True
    render_template = 'cascade/plugins/texticon.html'
    ring_plugin = 'IconPlugin'
    parent_classes = ('TextPlugin', )
    model_mixins = (TextIconModelMixin, )
    allow_children = False
    require_parent = False

    icon_font = GlossaryField(
        widgets.Select(),
        label=_("Font"),
    )

    symbol = GlossaryField(
        widgets.HiddenInput(),
        label=_("Select Symbol"),
    )

    glossary_field_order = ('icon_font', 'symbol')

    @classmethod
    def requires_parent_plugin(cls, slot, page):
        return False

    def get_plugin_urls(self):
        urls = [
            url(r'^wysiwig-config.js$',
                self.render_wysiwig_config,
                name='cascade_texticon_wysiwig_config'),
        ]
        return urls

    def render_wysiwig_config(self, request):
        context = {'icon_fonts': IconFont.objects.all()}
        javascript = render_to_string('cascade/admin/ckeditor.wysiwyg.txt',
                                      context)
        return HttpResponse(javascript, content_type='application/javascript')
Пример #28
0
class SimpleIconPlugin(IconPluginMixin, LinkPluginBase):
    name = _("Simple Icon")
    parent_classes = None
    require_parent = False
    allow_children = False
    render_template = 'cascade/plugins/simpleicon.html'
    model_mixins = (LinkElementMixin,)
    fields = list(LinkPluginBase.fields)
    ring_plugin = 'IconPlugin'

    icon_font = GlossaryField(
        widgets.Select(),
        label=_("Font"),
        initial=get_default_icon_font,
    )

    symbol = GlossaryField(
        widgets.HiddenInput(),
        label=_("Select Symbol"),
    )

    class Media:
        js = ['cascade/js/admin/iconplugin.js']

    glossary_field_order = ['icon_font', 'symbol']

    def get_form(self, request, obj=None, **kwargs):
        kwargs.update(form=VoluntaryLinkForm.get_form_class())
        return super(SimpleIconPlugin, self).get_form(request, obj, **kwargs)

    def render(self, context, instance, placeholder):
        context = super(SimpleIconPlugin, self).render(context, instance, placeholder)
        icon_font = self.get_icon_font(instance)
        symbol = instance.glossary.get('symbol')
        if icon_font and symbol:
            font_attr = 'class="{}{}"'.format(icon_font.config_data.get('css_prefix_text', 'icon-'), symbol)
            context['icon_font_attrs'] = mark_safe(font_attr)
        return context
Пример #29
0
class ExtendedSingletonObservablesFilter(django_filters.FilterSet):

    type__name = django_filters.CharFilter(lookup_type='icontains',
                                     label='Type contains')
    subtype__name = django_filters.CharFilter(lookup_type='icontains',
                                              label='Subtype')
    value = django_filters.CharFilter(lookup_type='icontains',
                                              label='Value contains')

    actionable_tags__info__name = django_filters.CharFilter(lookup_type='icontains',
                                              label='Tag contains')


    sources__import_info__name__OR__sources__top_level_iobject_identifier__latest__name = CharMultiFilter(lookup_type='icontains',
                                                           label='Report name contains')

    sources__import_info__name = django_filters.CharFilter(label='',widget=widgets.HiddenInput())
    sources__top_level_iobject_identifier__latest__name = django_filters.CharFilter(label='',widget=widgets.HiddenInput())

    test = forms.CharField(required=False,label="Test")
    
    class Meta:
        order_by = create_order_keyword_list(['type__name','subtype__name','value'])
        model = SingletonObservable
        fields = ['type__name',
                  'subtype__name',
                  'value',
                  'sources__import_info__name',
                  'sources__top_level_iobject_identifier__latest__name',
                  'actionable_tags__info__name'
                  ]


    #def clean(self):
    #    cleaned_data = super(ExtendedSingletonObservablesFilter, self).clean()
    #    cleaned_data['sources__top_level_iobject_identifier__latest__name'] = cleaned_data.get("sources__import_info__name")
    #    print "CLEANED %s" % cleaned_data
    #    return cleaned_data
Пример #30
0
class SearchForm(forms.Form):
    q = forms.CharField(
        widget=widgets.TextInput(
            attrs={
                'placeholder': 'Search...',
                'class': 'form-control'
            }
        ),
        validators=[MinLengthValidator(1)])
    type = forms.ChoiceField(
        initial='track',
        widget=widgets.HiddenInput(),
        choices=(
            ('track', 'Track'),
            ('album', 'Album'),
            ('artist', 'Artist'),
            ('playlist', 'Playlist'),
        ))

    def query_api(self):
        clean_data = self.cleaned_data
        url = SPOTIFY_API['search'] + urlencode(clean_data)
        return requests.get(url)