Esempio n. 1
0
 def testInitial(self):
     hf = forms.HtmlForm(SimpleForm)
     w = hf(initial = {'name':'luca','age':39,'profession':2})\
                 .addAttr('action','/test/')
     text = w.render()
     self.assertTrue('luca' in text)
     self.assertTrue('39' in text)
Esempio n. 2
0
 def testSimpleHtml(self):
     hf = forms.HtmlForm(SimpleForm)
     self.assertTrue('action' in hf.attributes)
     self.assertTrue('enctype' in hf.attributes)
     self.assertTrue('method' in hf.attributes)
     self.assertTrue(hf.form_class, SimpleForm)
     w = hf(action='/test/')
     self.assertTrue(isinstance(w.internal['form'], SimpleForm))
     self.assertEqual(w.attrs['action'], '/test/')
     self.assertEqual(w.attrs['method'], 'post')
Esempio n. 3
0
    def testUserChangeFormWidthModel(self):
        '''Test the UserChangeForm which provides boolean fields which
by default are true and some which are false.'''
        from djpcms.apps.user import UserChangeForm
        from stdcms.sessions import User
        from djpcms import forms, html
        html_form = forms.HtmlForm(UserChangeForm, model=User)
        fw = html_form()
        text = fw.render()
        self.assertTrue("type='checkbox'" in text)
        self.assertTrue("checked='checked" in text)
Esempio n. 4
0
 def testNotField(self):
     from djpcms import forms
     from djpcms.html import Div
     from djpcms.forms import layout as uni
     from djpcms.apps.contentedit import PageForm
     htmlform = forms.HtmlForm(PageForm,
                               layout=uni.FormLayout(Div(key='random')))
     layout = htmlform['layout']
     self.assertTrue('random' in layout)
     w = htmlform()
     text = w.render(context={'random': 'Hello'})
     self.assertTrue('<div>Hello</div>' in text)
Esempio n. 5
0
 def testLegend(self):
     from djpcms import forms
     from djpcms.forms import layout as uni
     from djpcms.apps.contentedit import PageForm
     htmlform = forms.HtmlForm(PageForm,
                               layout=uni.FormLayout(
                                   uni.Fieldset(legend='This is a legend')))
     layout = htmlform['layout']
     fs = layout[1]
     self.assertEqual(fs.legend_html, 'This is a legend')
     text = htmlform().render()
     self.assertTrue('This is a legend</div>' in text)
Esempio n. 6
0
    def testUserChangeForm(self):
        '''Test the UserChangeForm which provides boolean fields which
by default are true and some which are false.'''
        from djpcms.apps.user import UserChangeForm
        from djpcms import forms, html
        initials = dict(UserChangeForm.initials())
        self.assertEqual(initials,{'is_active':True})
        html_form = forms.HtmlForm(UserChangeForm)
        fw = html_form()
        text = fw.render()
        self.assertTrue("type='checkbox'" in text)
        self.assertTrue("checked='checked" in text)
Esempio n. 7
0
    def testColumnsFormtupleOfTuple(self):
        from djpcms import forms
        from djpcms.forms import layout as uni
        c = uni.Columns(('field1', 'field2'), 'field3')

        class Form(forms.Form):
            field1 = forms.CharField()
            field2 = forms.CharField()
            field3 = forms.CharField()

        form_html = forms.HtmlForm(Form, layout=uni.FormLayout(c))
        self.assertEqual(len(c.children), 2)
Esempio n. 8
0
 def __init__(self,
              name=None,
              parent_view=None,
              pagination=None,
              ajax_enabled=None,
              form=None,
              template_file=None,
              description=None,
              in_nav=None,
              has_plugins=None,
              insitemap=None,
              body_class=None,
              hidden=None,
              cache_control=None):
     self.name = name if name is not None else self.name
     self.description = description if description is not None else\
                         self.description
     self.parent_view = parent_view if parent_view is not None\
                              else self.parent_view
     self.pagination = pagination if pagination is not None\
                                  else self.pagination
     self.cache_control = cache_control or self.cache_control
     self.form = form if form is not None else self.form
     self.template_file = template_file or self.template_file
     if self.template_file:
         t = self.template_file
         if not (isinstance(t, list) or isinstance(t, tuple)):
             t = (t, )
         self.template_file = tuple(t)
     self.ajax_enabled = ajax_enabled if ajax_enabled is not None\
                                  else self.ajax_enabled
     self.hidden = hidden if hidden is not None else self.hidden
     if self.hidden:
         self.in_nav = 0
         self.insitemap = False
     else:
         self.in_nav = in_nav if in_nav is not None else self.in_nav
         self.insitemap = insitemap if insitemap is not None\
                             else self.insitemap
     self.has_plugins = has_plugins if has_plugins is not None else\
                          self.has_plugins
     if isinstance(form, forms.FormType):
         self.form = forms.HtmlForm(self.form)
     self.body_class = body_class if body_class is not None else\
                             self.body_class
     makename(self, self.name, self.description)
Esempio n. 9
0
def search_form(name='SearchForm',
                placeholder='search',
                input_name=None,
                submit=None,
                cn=None,
                choices=None,
                label='search text',
                deafult_style=uni.nolabel,
                on_submit=None,
                required=False,
                **kwargs):
    '''Create a new :class:`djpcms.forms.HtmlForm` for searching.

:parameter name: name of the :class:`Form`
:parameter placeholder: text for the ``placeholder`` input attribute.
:parameter submit: submit text. If not provided, the form will submit on enter
    key-stroke.
:parameter cn: additional class names for the input element in the form.
'''
    submit = submit or ()
    input_name = input_name or forms.SEARCH_STRING
    widget = html.TextInput(placeholder=placeholder, cn=cn)
    if not submit:
        widget.addData('options', {'submit': True})
        layout = uni.FormLayout(default_style=deafult_style)
    else:
        submit = ((submit, 'search'), )
        layout = uni.FormLayout(uni.Inlineset(input_name, uni.SUBMITS),
                                default_style=deafult_style)
    if choices:
        field = forms.ChoiceField(attrname=input_name,
                                  label=label,
                                  required=required,
                                  choices=choices,
                                  widget=widget)
    else:
        field = forms.CharField(attrname=input_name,
                                label=label,
                                required=required,
                                widget=widget)
    form_cls = forms.MakeForm(name, (field, ), on_submit=on_submit)

    return forms.HtmlForm(form_cls, inputs=submit, layout=layout, **kwargs)
Esempio n. 10
0
    def get_form(self,
                 request,
                 form_class=None,
                 instance=None,
                 addinputs=True,
                 **kwargs):
        '''Build a form. This method is called by editing/adding views.

:parameter form_class: form class to use.
:parameter instance: Instance of model or ``None`` or ``False``. If ``False``
    no instance will be passed to the form constructor.
    If ``None`` the instance will be obtained from '`request``.

    Default ``None``.

:parameter block: The content block holding the form.

:rtype: An instance of :class:`djpcms.forms.Form`.
'''
        # Check the Form Class
        form_class = form_class or self.form
        if not form_class:
            raise ValueError('Form class not defined for view "{0}" in\
 application "{1}" @ "{2}".\
 Make sure to pass a class form to the view or application constructor.'\
                    .format(request.view,self.__class__.__name__,self))
        elif isinstance(form_class, forms.FormType):
            form_class = forms.HtmlForm(form_class)
        # Check instance and model
        if instance == False:
            instance = None
        else:
            instance = instance or request.instance
        return get_form(request,
                        form_class,
                        instance=instance,
                        model=self.model,
                        addinputs=addinputs,
                        **kwargs)
Esempio n. 11
0
    def form(self):
        '''Build the form and the form layout'''
        from djpcms import forms
        from djpcms.forms import layout as uni

        class testForm(forms.Form):
            entry1__color = forms.CharField()
            entry1__size = forms.IntegerField()
            entry2__color = forms.CharField()
            entry2__size = forms.IntegerField()
            entry3__color = forms.CharField()
            entry3__size = forms.IntegerField()

        return forms.HtmlForm(
            testForm,
            layout=uni.FormLayout(
                uni.TableFormElement(
                    ('entry', 'color', 'size'),
                    ('entry1', 'entry1__color', 'entry1__size'),
                    ('entry2', 'entry2__color', 'entry2__size'),
                    ('entry3', 'entry3__color', 'entry3__size'),
                    key='table',
                    legend='Leggenda')))
Esempio n. 12
0
    tag = 'div'
    default_class = "fileupload-buttonbar"
    _media = media.Media(
        js=[
            media.jquerytemplate(), 'fileupload/jquery.fileupload.js',
            'fileupload/jquery.fileupload-ui.js', 'fileupload/upload.js'
        ],
        css={'screen': ['fileupload/jquery.fileupload-ui.css']})

    def stream(self, djp, widget, context):
        yield '<label class="fileinput-button">\
<span>Add files...</span>\
{0[inner]}\
</label>\
<button type="submit" class="start">Start upload</button>\
<button type="reset" class="cancel">Cancel upload</button>\
<button type="button" class="delete">Delete files</button>'.format(context)

    def media(self, djp=None):
        return self._media


FileUploadForm = forms.HtmlForm(UploadForm,
                                ajax=False,
                                layout=layout.FormLayout(
                                    layout.FormLayoutElement(
                                        'files',
                                        tag=None,
                                        field_widget_maker=FileInputHtml),
                                    form_messages_container_class=None),
                                inputs=[])
Esempio n. 13
0
class ChatForm(forms.Form):
    text = forms.CharField(required=False, widget=html.TextArea())

    def on_submit(self, commit):
        if commit:
            text = self.cleaned_data.get('text')
            if text:
                user = self.request.user
                msg = json.dumps({'user': to_string(user), 'message': text})
                self.request.appmodel.publish('chat', msg)
        return True


ChatFormHtml = forms.HtmlForm(ChatForm,
                              layout=uni.FormLayout(default_style=uni.nolabel),
                              inputs=(('submit', 'submit'), ))


class ChatApplication(views.Application):
    _media = media.Media(js=['djpsite/chat.js'])
    home = views.View()
    chat = views.View('chat', form=ChatFormHtml, has_plugins=True)

    def publish(self, channels, text):
        p = pubsub_server(self.settings)
        return p.publish(channels, text)

    def render(self, request, **kwargs):
        return html.Widget('div', cn='chatroom').render(request)
Esempio n. 14
0
class AddTheme(forms.Form):
    body = forms.FieldList(
        (theme_field(cssv.body.font_family), theme_field(
            cssv.body.font_size), theme_field(
                cssv.body.radius), theme_field(cssv.body.color, ColorField)),
        withprefix=False)


class ThemeInputs(forms.Form):
    '''input form for theme variables'''
    body = forms.FieldList((('color', ColorField), ('background', ColorField)))


AddThemeHtml = forms.HtmlForm(
    AddTheme,
    inputs=(('add new theme', 'add'), ),
)

ThemeInputsHtml = forms.HtmlForm(
    ThemeInputs, layout=uni.FormLayout(default_style=uni.inlineLabels))


class DesignApplication(views.Application):
    pagination = html.Pagination(('id', 'timestamp'))
    home = views.SearchView()
    add = views.AddView(form=AddThemeHtml, has_plugins=True, name='Add theme')
    view = views.ViewView()
    forms_view = views.View('/forms')

    def render_instance_default(self, request, instance, **kwargs):
        return get_form(request, ThemeInputsHtml)
Esempio n. 15
0
from djpcms import forms, html, media
from djpcms.forms import layout as uni

from .forms import *

__all__ = [
    'HtmlTemplateForm', 'HtmlPageForm', 'ContentBlockHtmlForm',
    'HtmlEditContentForm'
]

HtmlTemplateForm = forms.HtmlForm(TemplateForm)

HtmlPageForm = forms.HtmlForm(
    PageForm,
    layout=uni.FormLayout(
        uni.Columns(
            ('doctype', 'layout', 'inner_template', 'grid_system', 'url'),
            ('title', 'link', 'in_navigation', 'soft_root', uni.SUBMITS))),
    inputs=(('save', forms.SAVE_AND_CONTINUE_KEY), ))

ContentBlockHtmlForm = forms.HtmlForm(
    ContentBlockForm,
    inputs=(('save', forms.SAVE_KEY), ),
    layout=uni.FormLayout(
        uni.Fieldset('plugin_name', 'container_type', 'title'),
        uni.Inlineset('for_not_authenticated'),
        html.WidgetMaker(tag='div', key='plugin', cn='form-plugin-container')),
    media=media.Media(js=['djpcms/plugins/filters.js']))

HtmlEditContentForm = forms.HtmlForm(
    EditContentForm,
Esempio n. 16
0
                                                   ''):
            from akismet import Akismet
            from django.utils.encoding import smart_str
            akismet_api = Akismet(key=settings.AKISMET_API_KEY,
                                  blog_url='http://%s/' %
                                  Site.objects.get_current().domain)
            if akismet_api.verify_key():
                akismet_data = {
                    'comment_type': 'comment',
                    'referer': self.request.META.get('HTTP_REFERER', ''),
                    'user_ip': self.request.META.get('REMOTE_ADDR', ''),
                    'user_agent': self.request.META.get('HTTP_USER_AGENT', '')
                }
                if akismet_api.comment_check(smart_str(
                        self.cleaned_data['body']),
                                             data=akismet_data,
                                             build_data=True):
                    raise forms.ValidationError(
                        "Akismet thinks this message is spam")
        return self.cleaned_data['body']


HtmlContactForm = forms.HtmlForm(
    ContactForm,
    layout=FormLayout(Fieldset('name','email'),
                        Fieldset('body')),
    submits=(('Send message','contact'),),
    success_message=lambda request, response:\
                        "Your message has been sent. Thank you!"
)
Esempio n. 17
0
def html_plugin_form(form):
    if isinstance(form, forms.FormType):
        form = forms.HtmlForm(form)
    if isinstance(form,forms.HtmlForm):
        form.tag = None
    return form
Esempio n. 18
0
class UserAddForm(RegisterForm, UserChangeForm):
    pass


def change_password_message(request, user):
    if request.user == user:
        return '%s, you have successfully changed your password.' % user
    else:
        return 'Successfully changed password for %s.' % user

############################################################## FORM LAYOUTS

HtmlLoginForm = forms.HtmlForm(
    LoginForm,
    success_message = lambda request, user:\
     '%s successfully signed in' % user,
    inputs = (('Sign in','login_user'),)
)

HtmlLogoutForm = forms.HtmlForm(
    LogoutForm,
    layout=uni.SimpleLayout(html.Div(key='logout')),
    inputs=(('logout', 'logout'),)
)

HtmlAddUserForm = forms.HtmlForm(
    UserAddForm,
    layout = uni.FormLayout(uni.Fieldset('username','password','re_type')),
    success_message = lambda request, user:\
        'User "%s" successfully created.' % user,
    inputs = (('create','create'),)
Esempio n. 19
0
    descending = forms.BooleanField(initial=False)
    headers = forms.ChoiceField(required=False,
                                widget=html.Select(cn='model-fields'),
                                choices=FieldChoices(multiple=True))
    table_footer = forms.BooleanField(initial=False, label='footer')
    display_if_empty = forms.BooleanField(initial=False)


HtmlModelListForm = forms.HtmlForm(
    ModelItemListForm,
    layout=uni.FormLayout(uni.Fieldset('for_model', 'text_search', 'filter',
                                       'exclude'),
                          uni.Inlineset('order_by',
                                        'descending',
                                        label='Ordering'),
                          uni.Inlineset('max_display',
                                        'display_if_empty',
                                        'table_footer',
                                        label='Max display'),
                          uni.Fieldset('headers'),
                          tag='div',
                          cn='model-filters'),
)


class FormModelForm(ForModelForm):
    method = forms.ChoiceField(choices=(('get', 'get'), ('post', 'post')),
                               initial='get')
    ajax = forms.BooleanField(initial=False)