示例#1
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)
示例#2
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)
示例#3
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)
示例#4
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}))
示例#5
0
def profile_edit(request, template_name="profiles/profile_edit.html"):

    profile = request.user.get_profile()
    form = ProfileForm(request.POST or None, instance=profile)

    if form.is_valid():
        print form.instance.__dict__
        form.save()
        msg = 'Profile edited'
        messages.add_message(request, messages.INFO, msg)
        return HttpResponseRedirect(reverse("profile_detail", kwargs={"github_account": profile.github_account}))

    # TODO - move this to a template
    github_account = """
    <div
        id="div_id_github_account"
        class="ctrlHolder"><label for="id_github_account" >Github account</label><strong>{0}</strong></div>
    """.format(profile.github_account)

    helper = FormHelper()
    helper.form_class = "profile-edit-form"
    helper.layout = Layout(
        Fieldset(
            '',
            HTML(github_account),
            'bitbucket_url',
            'google_code_url',
        ),
        ButtonHolder(
            Submit('edit', 'Edit', css_class="awesome forestgreen"),
        )
    )

    return render(request, template_name,
        {
            "profile": profile,
            "form": form,
            "helper": helper,
        })
示例#6
0
文件: forms.py 项目: banabana/fsb
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
示例#7
0
    def get_form_class(self, unique_form_id=None):
        """
        Constructs a real django.forms Form() class out of this ContactForm instance and provides
        functionality for handling form submission.
        """

        ContactFormFormBase = self.get_form_base_class()

        attrs = {
            'model_instance_id': self.id,
            'contactform_id': forms.CharField(initial=self.pk, widget=HiddenInput),
            'model': self.__class__,
        }
        if unique_form_id:
            attrs['unique_form_id'] = forms.CharField(initial=unique_form_id, widget=HiddenInput)

        count = -1
        layout = ["contactform_id"]

        for field in self.field_set.all().order_by("position"):
            count += 1
            if field.widget == '':
                widget = None
            else:
                widget = load_class(field.widget)
            label = field.label
            field_class = load_class(field.field_type)
            if issubclass(field_class, BooleanField):
                label=mark_safe(label)
                if field.initial and field.initial.lower() in ['1','checked','yes','true']:
                    checked = True
                else:
                    checked = False
                form_field = field_class(required=field.required, widget=widget, label=label,initial=checked)
            elif issubclass(field_class, ChoiceField):
                txt_choices = field.choices.replace('\n','').replace('\r','').split(';')
                choices = []
                for txt in txt_choices:
                    txt = txt.strip()
                    if txt != '':
                        choices.append( (slugify(strip_tags(txt)), mark_safe(txt)) )
                try:
                    initial = choices[int(field.initial.strip())-1][0]
                except:
                    initial=None
                form_field = field_class(required=field.required, widget=widget,
                                         label=label, initial=initial,
                                         choices=choices)
                # ..., initial=field.initial, help_text=field.help_text)
            elif issubclass(field_class, FileField):
                form_field = field_class(required=field.required, widget=widget,
                                         label=u'%s (%s %s)' % (label, _('max.'), filesizeformat(MAX_FILE_SIZE)),
                                         initial=field.initial)
                # ..., initial=field.initial, help_text=field.help_text)
            elif field_class is TitlePseudoField:
                if "uni_form" in settings.INSTALLED_APPS:
                    from uni_form.helpers import HTML
                    layout.append(HTML(u"<h3>%s</h3>" % label))
                continue
            else:
                form_field = field_class(required=field.required, widget=widget,
                                         label=label, initial=field.initial)
                # ... , initial=field.initial, help_text=field.help_text)
            layout.append("%s_%s" % (slugify(field.label), count))
            if field.css_class:
                form_field.widget.attrs['class'] = field.css_class
            attrs["%s_%s" % (slugify(field.label), count)] = form_field

        has_captcha = 'captcha' in settings.INSTALLED_APPS and self.has_captcha
        attrs['has_captcha'] = has_captcha

        if has_captcha:
            from captcha.fields import CaptchaField
            attrs['captcha'] = CaptchaField(label=_("Enter the characters showed in the image below."))

        if "uni_form" in settings.INSTALLED_APPS:
            attrs['uni_form_helper'] = _make_helper(layout)
        
        form_class = type(smart_str(slugify(self.name) + 'Form'), (ContactFormFormBase,), attrs)
        return form_class