Exemplo n.º 1
0
    def test_change_layout_dynamically_delete_field(self):
        template = get_template_from_string(u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """)

        form = TestForm()
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                Fieldset(
                    u'Company Data',
                    'is_company',
                    'email',
                    'password1',
                    'password2',
                    css_id="multifield_info",
                ), Column(
                    'first_name',
                    'last_name',
                    css_id="column_name",
                )))

        # We remove email field on the go
        # Layout needs to be adapted for the new form fields
        del form.fields['email']
        del form_helper.layout.fields[0].fields[1]

        c = Context({'form': form, 'form_helper': form_helper})
        html = template.render(c)
        self.assertFalse('email' in html)
Exemplo n.º 2
0
def advanced_search(request, reset=False):
    marketplace = request.marketplace

    if reset:
        form = AdvancedSearchForm(marketplace=marketplace)
    else:
        form = AdvancedSearchForm(marketplace=marketplace, data=request.GET)

    if request.GET.get("do"):

        result_list = []
        if form.is_valid():

            result_list = form.search()

            pager = Paginator(result_list,
                              settings.HAYSTACK_SEARCH_RESULTS_PER_PAGE)

            try:
                page = int(request.GET.get("page", "1"))
            except:
                page = 1

            try:
                paginator = pager.page(page)
            except (EmptyPage, InvalidPage):
                raise Http404

            paged = (pager.num_pages > 1)

            return render_to_response(
                "%s/buy/advanced_search_results.html" %
                marketplace.template_prefix, {
                    "result_list": paginator,
                    "form": form,
                    "pages": pager.page_range,
                    "paged": paged,
                    "total": pager.count,
                    "view_mode": form.cleaned_data["view_by"]
                }, RequestContext(request))

    form_helper = FormHelper()
    layout = Layout(
        Fieldset("", "q"),
        Fieldset("", Row("categories", "subcategories")),
        Fieldset("", "include"),
        Fieldset("", Row("from_price", "to_price")),
        Fieldset("", "sort"),
        Fieldset("", "view_by"),
    )
    form_helper.add_layout(layout)
    submit = Submit("do", _("Search"))
    submit.field_classes = "button_primary"
    form_helper.add_input(submit)

    return render_to_response(
        "%s/buy/advanced_search.html" % marketplace.template_prefix, {
            "form": form,
            "helper": form_helper
        }, RequestContext(request))
Exemplo n.º 3
0
    def setUp(self):

        self.style = '<style>.formRow{color:red;}</style>'

        layout = Layout(
            # first fieldset shows the company
            Fieldset('', 'is_company'),
            # second fieldset shows the contact info
            Fieldset(
                'Contact details',
                'email',
                Row('password1', 'password2'),
                'first_name',
                'last_name',
            ))

        form_helper = FormHelper()
        form_helper.add_layout(layout)

        self.c = Context({
            'formset': TestFormset(),
            'formset_helper': form_helper
        })

        template = get_template_from_string("""
{% load uni_form_tags %}
{% uni_form_set formset formset_helper %}
        """)
        self.html = template.render(self.c)
Exemplo n.º 4
0
class LayoutTestForm(forms.Form):

    is_company = forms.CharField(label="company",
                                 required=False,
                                 widget=forms.CheckboxInput())
    email = forms.CharField(label="email",
                            max_length=30,
                            required=True,
                            widget=forms.TextInput())
    password1 = forms.CharField(label="password",
                                max_length=30,
                                required=True,
                                widget=forms.PasswordInput())
    password2 = forms.CharField(label="re-enter password",
                                max_length=30,
                                required=True,
                                widget=forms.PasswordInput())
    first_name = forms.CharField(label="first name",
                                 max_length=30,
                                 required=True,
                                 widget=forms.TextInput())
    last_name = forms.CharField(label="last name",
                                max_length=30,
                                required=True,
                                widget=forms.TextInput())

    # Attach a formHelper to your forms class.
    helper = FormHelper()

    # create some HTML that you want in the page
    style = """
    <style>
        .formRow {
            color: red;
        }
    </style>
    
    """
    # create the layout object
    layout = Layout(
        # first fieldset shows the company
        Fieldset('', 'is_company'),

        # second fieldset shows the contact info
        Fieldset(
            'Contact details',
            HTML(style),
            'email',
            Row('password1', 'password2'),
            'first_name',
            'last_name',
        ))

    helper.add_layout(layout)

    submit = Submit('add', 'Add this contact')
    helper.add_input(submit)
Exemplo n.º 5
0
    def test_layout_within_layout(self):
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                Layout(
                    MultiField(
                        "Some company data",
                        'is_company',
                        'email',
                        css_id="multifield_info",
                    ), ),
                Column(
                    'first_name',
                    # 'last_name', Missing a field on purpose
                    css_id="column_name",
                    css_class="columns",
                ),
                ButtonHolder(Submit('Save', 'Save',
                                    css_class='button white'), ),
                Div(
                    'password1',
                    'password2',
                    css_id="custom-div",
                    css_class="customdivs",
                )))

        template = get_template_from_string(u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        html = template.render(c)

        self.assertTrue('multiField' in html)
        self.assertTrue('formColumn' in html)
        self.assertTrue('id="multifield_info"' in html)
        self.assertTrue('id="column_name"' in html)
        self.assertTrue('class="formColumn columns"' in html)
        self.assertTrue('class="buttonHolder">' in html)
        self.assertTrue('input type="submit"' in html)
        self.assertTrue('name="save"' in html)
        self.assertTrue('id="custom-div"' in html)
        self.assertTrue('class="customdivs"' in html)
        self.assertTrue('last_name' in html)
Exemplo n.º 6
0
    def test_double_rendered_field(self):
        form = TestForm()

        form_helper = FormHelper()
        form_helper.add_layout(Layout('is_company', 'is_company'))

        template = get_template_from_string(u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        settings.UNIFORM_FAIL_SILENTLY = False
        self.assertRaises(Exception, lambda: template.render(c))
        del settings.UNIFORM_FAIL_SILENTLY
Exemplo n.º 7
0
    def test_formset_layout(self):
        template = get_template_from_string(u"""
            {% load uni_form_tags %}
            {% uni_form testFormSet formset_helper %}
        """)

        form_helper = FormHelper()
        form_helper.form_id = 'thisFormsetRocks'
        form_helper.form_class = 'formsets-that-rock'
        form_helper.form_method = 'POST'
        form_helper.form_action = 'simpleAction'
        form_helper.add_layout(
            Layout(
                Fieldset(
                    "Item {{ forloop.counter }}",
                    'is_company',
                    'email',
                ),
                HTML(
                    "{% if forloop.first %}Note for first form only{% endif %}"
                ), Row('password1', 'password2'),
                Fieldset("", 'first_name', 'last_name')))

        TestFormSet = formset_factory(TestForm, extra=3)
        testFormSet = TestFormSet()

        c = Context({
            'testFormSet': testFormSet,
            'formset_helper': form_helper,
            'csrf_token': _get_new_csrf_key()
        })
        html = template.render(c)

        # Check form parameters
        self.assertEqual(html.count('<form'), 1)
        self.assertEqual(
            html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1)

        self.assertTrue('class="uniForm formsets-that-rock"' in html)
        self.assertTrue('method="post"' in html)
        self.assertTrue('id="thisFormsetRocks">' in html)
        self.assertTrue('action="%s"' % reverse('simpleAction') in html)

        # Check form layout
        self.assertTrue('Item 1' in html)
        self.assertTrue('Item 2' in html)
        self.assertTrue('Item 3' in html)
        self.assertEqual(html.count('Note for first form only'), 1)
        self.assertEqual(html.count('formRow'), 3)
Exemplo n.º 8
0
    def test_layout_invalid_unicode_characters(self):
        # Adds a BooleanField that uses non valid unicode characters "ñ"
        form = TestForm()

        form_helper = FormHelper()
        form_helper.add_layout(Layout('españa'))

        template = get_template_from_string(u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        settings.UNIFORM_FAIL_SILENTLY = False
        self.assertRaises(Exception, lambda: template.render(c))
        del settings.UNIFORM_FAIL_SILENTLY
Exemplo n.º 9
0
    def test_i18n(self):
        template = get_template_from_string(u"""
            {% load uni_form_tags %}
            {% uni_form form form.helper %}
        """)
        form = TestForm()
        form_helper = FormHelper()
        form_helper.layout = Layout(
            HTML(_("i18n text")),
            Fieldset(
                _("i18n legend"),
                'first_name',
                'last_name',
            ))
        form.helper = form_helper

        html = template.render(Context({'form': form}))
Exemplo n.º 10
0
    def test_layout_fieldset_row_html_with_unicode_fieldnames(self):
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                Fieldset(u'Company Data',
                         u'is_company',
                         css_id="fieldset_company_data",
                         css_class="fieldsets"),
                Fieldset(
                    u'User Data',
                    u'email',
                    Row(u'password1',
                        u'password2',
                        css_id="row_passwords",
                        css_class="rows"),
                    HTML('<a href="#" id="testLink">test link</a>'),
                    HTML(u"""
                        {% if flag %}{{ message }}{% endif %}
                    """),
                    u'first_name',
                    u'last_name',
                )))

        template = get_template_from_string(u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """)
        c = Context({
            'form': TestForm(),
            'form_helper': form_helper,
            'flag': True,
            'message': "Hello!",
        })
        html = template.render(c)

        self.assertTrue('id="fieldset_company_data"' in html)
        self.assertTrue('class="fieldsets' in html)
        self.assertTrue('id="row_passwords"' in html)
        self.assertTrue('class="formRow rows"' in html)
        self.assertTrue('Hello!' in html)
        self.assertTrue('testLink' in html)
Exemplo n.º 11
0
    def helper(self):
        helper = FormHelper()
        helper.add_input(Submit('submit', _('Submit!')))

        layout = Layout(
                Fieldset('', 
                    'name', 'description'),
                Fieldset(_('When and where'),
                    'date', 'time',
                    'town', 'other_town',
                    'place',
                    ),
                Fieldset(_('Details'),
                    'organizer', 'link', 'contact', 'image',
                    ),
                )

        helper.add_layout(layout)
        helper.form_action = reverse('agenda:create')
        helper.form_method = 'post'
        helper.form_style = 'inline'
        return helper
Exemplo n.º 12
0
    class CustomXFormForm(forms.ModelForm):
        def clean(self):
            cleaned = super(CustomXFormForm, self).clean()

            # if they are restricting to a group
            if cleaned['restrict_to'] and not cleaned['restrict_message']:
                raise forms.ValidationError(
                    "You must enter a message to display if you are restricting the form."
                )

            return cleaned

        class Meta:
            model = XForm
            fields = form_fields

        helper = FormHelper()
        layout = Layout(
            # required fields
            Fieldset(*required_fields),

            # optional attributes
            Fieldset(
                'Advanced Settings',
                'keyword_prefix',
                'command_prefix',
                'separator',
            ),

            # security
            Fieldset(
                'Security',
                'restrict_to',
                'restrict_message',
            ))

        helper.add_layout(layout)
Exemplo n.º 13
0
class PrepaidStartForm(PrepaidForm):
    helper = FormHelper()
    submit = Submit('activate', _(u'Activate'))
    helper.add_input(submit)

    username = forms.RegexField(
        regex=r'^\w+$',
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_(u"Username"),
        error_messages={
            'invalid':
            _(u"This value must contain only letters, numbers and underscores."
              )
        })
    email = forms.EmailField(label=_(u"Email address"), required=False)
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
                                                           render_value=False),
                                label=_(u"Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
                                                           render_value=False),
                                label=_(u"Password (again)"))
    tos = forms.BooleanField(
        widget=forms.CheckboxInput(attrs=attrs_dict),
        label=_(u'I have read and agree to the Terms of Service'),
        error_messages={
            'required': _(u"You must agree to the terms to register")
        })
    first_name = forms.CharField(label=_(u"first name"),
                                 max_length=30,
                                 required=False,
                                 widget=forms.TextInput())
    last_name = forms.CharField(label=_(u"last name"),
                                max_length=30,
                                required=False,
                                widget=forms.TextInput())

    detail_help = _(u'Note. An optional field to fill.')
    email_help = _(
        u'Note. Your email address will not show anyone else. If you do not fill in this field, and forget your password you can not recover it.'
    )
    password_help = _(
        u'From 6 to 20 characters, only letters and numbers. Note. Your password will not be shown to anyone else.'
    )
    layout = Layout(
        Fieldset(
            u'',
            'prnumber',
            'prcode',
        ),
        Fieldset(
            u'',
            'username',
            Row('password1', 'password2'),
            HTML(password_help),
        ),

        # second fieldset shows the contact info
        Fieldset(
            _(u'Additional Information'),
            HTML(detail_help),
            'email',
            HTML(email_help),
            'first_name',
            'last_name',
        ),
        Fieldset(
            u'',
            'tos',
        ))

    helper.add_layout(layout)

    def __init__(self, request, *args, **kwargs):
        super(PrepaidStartForm, self).__init__(*args, **kwargs)
        self.user = request.user
        self.ip = request.META['REMOTE_ADDR']
        self.user_exits = True

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.

        """
        try:
            user = User.objects.get(
                username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        self.user_exits = False
        raise forms.ValidationError(
            _(u"A user with that username already exists."))

    @transaction.commit_on_success
    def save_prepaid(self, card):
        try:
            #log.debug('email({0})'.format(self.data.get('email')))
            new_user = User.objects.create_user(self.data.get('username'), '',
                                                self.data.get('password1'))
            new_user.is_active = True
            user_group = Group.objects.get(name="user")
            new_user.groups.add(user_group)
            new_user.save()
            new_endpoint = Endpoint.objects.create_endpoint(
                new_user, self.data.get('prnumber'))
            #

            bal = Balance.objects.get(
                accountcode__username__exact=self.data.get('username'))
            pay_date = datetime.datetime.now()
            name = 'add:::lincom3000:::prepaid:::{0}'.format(card.pk)
            comments = 'Added Start Paskage'
            method = 'from site prepaid'

            code = "{0}{1}{2}".format(name, comments, method)
            mcode = hashlib.md5()
            mcode.update(code.upper())

            temp_txt = "".join([str(random.randint(0, 9)) for i in range(20)])
            pay_transaction_id = "{0}X{1}".format(int(time.time()), temp_txt)
            up_ball = Balance.objects.filter(
                accountcode__username__exact=self.data.get('username')).update(
                    cash=F('cash') + card.start_balance)
            #log.debug("Prepaid enabled {0}".format(card.enabled))
            b = BalanceHistory.objects.create(
                name=name,
                accountcode=bal,
                site=bal.site,
                pay_date=pay_date,
                method=method,
                amount=Decimal(card.start_balance),
                transaction_id=pay_transaction_id,
                details=comments,
                reason_code=mcode.hexdigest())
            b.success = True
            b.save()
            card.enabled = True
            card.save()
            return new_endpoint
        except:
            #log.error(e)
            #transaction.rollback()
            history = PrepaidLog.objects.create_history(
                self.ip,
                self.data.get("prnumber"),
                code=self.data.get("prcode"),
                st=4,
                nt=2)
            return False

    def clean(self):
        fl_error = False
        nt = 3
        st = 4
        log.debug("len username: {0} user_exits:{1} tos:{2}".format(
            self.data.get('username'), self.user_exits, self.data.get('tos')))

        if self.user_exits and self.data.get('username') is not None and len(
                self.data.get('username')) > 0 and self.data.get(
                    'tos') is not None:
            if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
                if self.cleaned_data['password1'] != self.cleaned_data[
                        'password2']:
                    raise forms.ValidationError(
                        _(u"The two password fields didn't match."))
                else:
                    try:
                        #log.debug("number: {0} (user:{1}) ip: {2}".format(self.data.get("prnumber"), self.user, self.ip))
                        prc = Prepaid.objects.get(
                            num_prepaid__iexact=self.data.get("prnumber"))
                    except Prepaid.DoesNotExist:
                        #log.error("prnumber: {0} (user:{1}) ip: {2}".format(self.data.get("prnumber"), self.user, self.ip))
                        history = PrepaidLog.objects.create_history(
                            self.ip, self.data.get("prnumber"))
                        #log.error(history.st)
                        raise forms.ValidationError(
                            _(u"Incorrect number or the code of the card."))
                    try:
                        #log.debug("number: {0} code:{3} (user:{1}) ip: {2}".format(self.data.get("prnumber"), self.user, self.ip, self.data.get("prcode")))
                        card = Prepaid.objects.is_card(
                            self.data.get("prnumber"), self.data.get("prcode"))
                        #log.debug("card: {0}".format(card))
                        if card:
                            if card.enabled:
                                st = 3
                                nt = card.nt
                                fl_error = True
                            elif card.is_valid:
                                st = 1
                                nt = card.nt
                                fl_error = True
                            elif card.nt == 2:

                                log.debug("RUN save_prepaid")
                                new_endpoint = self.save_prepaid(card)
                                if new_endpoint:
                                    nt = card.nt
                                    st = 5
                                else:
                                    raise forms.ValidationError(
                                        _(u"System error no activate prepaid card!"
                                          ))
                            else:
                                st = 6
                                nt = card.nt
                                fl_error = True
                        else:
                            st = 2
                            fl_error = True
                    except:
                        #log.error("number: {0} (user:{1}) ip: {2}".format(self.data.get("prnumber"), self.user, self.ip))
                        #raise forms.ValidationError(_("System error no activate prepaid card!"))
                        raise forms.ValidationError(
                            _(u"Incorrect number or the code of the card."))
                    history = PrepaidLog.objects.create_history(
                        self.ip,
                        self.data.get("prnumber"),
                        code=self.data.get("prcode"),
                        st=st,
                        nt=nt)
                    if fl_error:
                        raise forms.ValidationError(
                            _(u"Incorrect number or the code of the card."))
            return self.cleaned_data
Exemplo n.º 14
0
def _make_helper(layout_fields):
    from uni_form.helpers import Layout, Fieldset, FormHelper
    helper = FormHelper()
    helper.add_layout(Layout(*[str(field) if isinstance(field, basestring) else field for field in layout_fields]))
    return helper
Exemplo n.º 15
0
class RegistrationForm(forms.Form):
    """
    Form for registering a new user account.
    
    Validates that the requested username is not already in use, and
    requires the password to be entered twice to catch typos.
    
    """
    username = forms.CharField(
        widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=30)),
        label=_("User name"))

    email = forms.EmailField(
        widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)),
        label=_("Email address"))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
                                                           render_value=False),
                                label=_("Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict,
                                                           render_value=False),
                                label=_("Password (again)"))

    helper = FormHelper()
    layout = Layout(
        'username',
        'email',
        Row('password1', 'password2'),
    )

    helper.add_layout(layout)

    submit = Submit('register', 'Register')
    helper.add_input(submit)

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.
        
        """
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(
                    _("The two password fields didn't match."))
        return self.cleaned_data

    def clean_username(self):
        """
        Validate that the supplied email address is unique for the
        site.

        """
        if User.objects.filter(username__exact=self.cleaned_data['username']):
            raise forms.ValidationError(
                _("This username is already in use. Please supply a different username."
                  ))
        return self.cleaned_data['username']

    def clean_email(self):
        """
        Validate that the supplied email address is unique for the
        site.

        """
        if User.objects.filter(email__iexact=self.cleaned_data['email']):
            raise forms.ValidationError(
                _("This email address is already in use. Please supply a different email address."
                  ))
        return self.cleaned_data['email']