コード例 #1
0
ファイル: views.py プロジェクト: sbadisa/django-form-builder
def dynform(request):
    if request.method == 'GET':
        form = BaseDynamicForm.get_form(
            constructor_dict=constructor_dict,
            #data=data,
            #files=files,
            remove_filefields=False,
            remove_datafields=False)
    # if POST (form submitted)
    else:
        form = BaseDynamicForm.get_form(constructor_dict=constructor_dict,
                                        data=request.POST,
                                        files=request.FILES,
                                        remove_filefields=False,
                                        remove_datafields=False)

        if form.is_valid():
            messages.add_message(request, messages.SUCCESS, "form is valid")
        else:
            # show all error messages
            for k, v in get_labeled_errors(form).items():
                messages.add_message(request, messages.ERROR,
                                     "<b>{}</b>: {}".format(k, strip_tags(v)))

    d = {'form': form}
    return render(request, "form.html", d)
コード例 #2
0
 def test_getform(self):
     """
     Test init form with build_constructor_dict() and fields list
     """
     constructor_dict = BaseDynamicForm.build_constructor_dict(self.fields)
     form = BaseDynamicForm.get_form(constructor_dict=constructor_dict,
                                     data=self.data)
     logger.info("Test form with dynamic fields (build_constructor_dict())")
     assert form.is_valid()
コード例 #3
0
 def test_compiledform_readonly(self):
     """
     Test compiled_form_readonly() method
     """
     constructor_dict = BaseDynamicForm.build_constructor_dict(self.fields)
     form = BaseDynamicForm.get_form(constructor_dict=constructor_dict,
                                     data=self.data)
     SavedFormContent.compiled_form_readonly(form)
     logger.info("Test test_compiledform_readonly()")
     assert form.is_valid()
コード例 #4
0
def urlshortener(request):
    urlsh = None
    tinyurl = ''
    # captcha, captcha_img, captcha_hidden = get_captcha()
    url = dict(request.GET).get('url', '')

    initial = {
        # 'captcha_hidden': captcha_hidden,
        'url': url[0] if url else ''
    }

    if request.method == 'GET':
        form = UrlShortenerForm(initial=initial)
        form_captcha = BaseDynamicForm.get_form(
            constructor_dict=constructor_dict)
    elif request.method == 'POST':
        # clean oldies
        clean_expired_urls()
        form = UrlShortenerForm(data=request.POST)
        form_captcha = BaseDynamicForm.get_form(
            constructor_dict=constructor_dict, data=request.POST)

        if not all((form.is_valid(), form_captcha.is_valid())):
            messages.add_message(
                request, messages.ERROR,
                _('I valori da te inseriti non risultano validi.'))
            initial['url'] = form.data.get('url')
            form = UrlShortenerForm(initial=initial)
        else:
            # recyple already forged tinyurls
            urlsh = UrlShortener.objects.filter(
                original_url=form.cleaned_data['url']).first()
            if not urlsh:
                entry = dict(original_url=form.cleaned_data['url'],
                             user_id=request.user
                             if request.user.is_authenticated else None)
                urlsh = UrlShortener.objects.create(**entry)
                urlsh.set_shorten_url()
            tinyurl = urlsh.get_redirect_url(request)

    context = dict(
        project_name=_PROJECT_NAME,
        form=form,
        form_captcha=form_captcha,
        delta_days=DELTA_DAYS,
        urlsh=urlsh,
        # captcha_img = captcha_img,
        tinyurl=tinyurl)
    return render(request, TINYURL_TEMPLATE, context)
コード例 #5
0
ファイル: base.py プロジェクト: sbadisa/django-form-builder
 def get_baseform(self, initial_fields, data={}, files={}):
     """
     Build a form from BaseDynamicForm
     """
     form = BaseDynamicForm.get_form(initial_fields=initial_fields,
                                     data=data,
                                     files=files)
     return form
コード例 #6
0
 def test_compiledform(self):
     """
     Test compiled_form() method
     """
     constructor_dict = BaseDynamicForm.build_constructor_dict(self.fields)
     form = SavedFormContent.compiled_form(
         data_source=json.dumps(self.data))
     logger.info("Test compiledform()")
     assert form.is_valid()
コード例 #7
0
def ask(request):
    cdict = copy.copy(settings.REGISTRATION_CAPTCHA_FORM)

    if request.method == 'GET':
        form_captcha = BaseDynamicForm.get_form(
            constructor_dict=cdict,
            custom_params={'lang': translation.get_language()})
        d = dict(form=AskForm_1(), form_captcha=form_captcha)

        return render(request, 'ask.html', d)
    else:
        form = AskForm_1(request.POST)
        form_captcha = BaseDynamicForm.get_form(constructor_dict=cdict,
                                                data=request.POST)

        if not (form.is_valid() and form_captcha.is_valid()):
            dform = str(dict(form.cleaned_data))
            logger.error('Registration form is not valid: {}'.format(dform))
            return render(request, 'ask.html', {
                'form': form,
                'form_captcha': form_captcha
            })
        # validate tin
        validate_tin_func_name = settings.TIN_VALIDATION_FUNC
        validate_tin_func = import_string(validate_tin_func_name)

        if not validate_tin_func(form.cleaned_data['tin']):
            logger.error('Registration form is not valid, tin validation failed: {}'\
                          .format(form.cleaned_data['tin']))
            return render(
                request,
                'custom_message.html',
                dict(title=_('TIN code validation failed'),
                     avviso=_(
                         'It have been occurred an error validating your TIN'),
                     description=''),
                status=403)

        # it seems quite good, check its delivery address
        serialized_dict = serialize_dict(form.cleaned_data)

        token = create_registration_token(serialized_dict)
        _msg = _(
            '{} {} [{}] [{}] have requested to be registered as a new user.')
        logger.info(
            _msg.format(form.cleaned_data['name'],
                        form.cleaned_data['surname'],
                        form.cleaned_data['mail'], form.cleaned_data['tin']))
        request_fqdn = build_registration_token_url(request, token)

        mail_body = dict(name='{} {}'.format(form.cleaned_data['name'],
                                             form.cleaned_data['surname']),
                         url=request_fqdn)

        mail_sent = send_mail(
            settings.REGISTRATION_ASK_OBJ,
            settings.REGISTRATION_ASK_BODY.format(**mail_body),
            settings.DEFAULT_FROM_EMAIL,
            [form.cleaned_data['mail']],  # it's a list :)
            fail_silently=True)
        if not mail_sent:
            logger.error('Email to {} cannot be send.'.format(
                form.cleaned_data['mail']))

            return render(request,
                          'custom_message.html',
                          dict(title=_('Email send error'),
                               avviso=_(
                                   'It have been occurred an Error '
                                   'sending the confirmation email to you'),
                               description=_('Please try later.')),
                          status=403)
        else:
            return HttpResponseRedirect(
                reverse('unical_template:confirmation-email'))