• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.Form类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中models.Form的典型用法代码示例。如果您正苦于以下问题:Python Form类的具体用法?Python Form怎么用?Python Form使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Form类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: post

    def post(self):
        try:
            jsondata = json.loads(self.request.body)
        except UnicodeDecodeError:
            jsondata = json.loads(self.request.body,encoding='latin-1')

        logging.info(jsondata.keys())

        form = Form()
        
        procfields = []
        for i,f in enumerate(jsondata['fields']):
            procfields.append({
                'name': 'field{}'.format(i),
                'Descr': f['Descr'],
                'Val': f['Val']
                })
        
        form.creator = jsondata['creator']
        form.until = datetime.datetime.now() + datetime.timedelta(hours=jsondata['duration'])
        form.hashtag = jsondata['hashtag']
        form.fields = procfields
        form.description = jsondata['description']
        form.authenticated = not bool(jsondata['authenticated']) 
        form.info = jsondata['info']

        form.put()
开发者ID:guillemborrell,项目名称:btdotnet,代码行数:27,代码来源:rest.py


示例2: post

	def post(self):
		form = Form()
		self._update_form_from_request(form)
		
		form.put()
		
		logging.info("Created form '%s'" % form.key.urlsafe())
		
		self.redirect(self.uri_for('forms-list'))
开发者ID:vanderkleij,项目名称:MailFacade,代码行数:9,代码来源:admin.py


示例3: form_toggle

def form_toggle(hashid):
    form = Form.get_with_hashid(hashid)

    # check that this request came from user dashboard to prevent XSS and CSRF
    referrer = referrer_to_baseurl(request.referrer)
    service = referrer_to_baseurl(settings.SERVICE_URL)
    if referrer != service:
        return render_template('error.html',
                               title='Improper Request',
                               text='The request you made is not valid.<br />Please visit your dashboard and try again.'), 400

    if form.owner_id != current_user.id:
        if form not in current_user.forms: #accounts for bug when form isn't assigned owner_id bc it was not created from dashboard
            return render_template('error.html',
                                  title='Wrong user',
                                  text='You aren\'t the owner of that form.<br />Please log in as the form owner and try again.'), 400
    if not form:
            return render_template('error.html',
                                   title='Not a valid form',
                                   text='That form does not exist.<br />Please check the link and try again.'), 400
    else:
        form.disabled = not form.disabled
        DB.session.add(form)
        DB.session.commit()
        if form.disabled:
            flash('Form successfully disabled', 'success')
        else:
            flash('Form successfully enabled', 'success')
        return redirect(url_for('dashboard'))
开发者ID:webscienceco,项目名称:formspree,代码行数:29,代码来源:views.py


示例4: submission_deletion

def submission_deletion(hashid, submissionid):
    submission = Submission.query.get(submissionid)
    form = Form.get_with_hashid(hashid)

    # check that this request came from user dashboard to prevent XSS and CSRF
    referrer = referrer_to_baseurl(request.referrer)
    service = referrer_to_baseurl(settings.SERVICE_URL)
    if referrer != service:
        return render_template('error.html',
                               title='Improper Request',
                               text='The request you made is not valid.<br />Please visit your dashboard and try again.'), 400

    if form.owner_id != current_user.id:
        if form not in current_user.forms: #accounts for bug when form isn't assigned owner_id bc it was not created from dashboard
            return render_template('error.html',
                                  title='Wrong user',
                                  text='You aren\'t the owner of that form.<br />Please log in as the form owner and try again.' + str(form.id)), 400
    if not submission:
        return render_template('error.html',
                              title='Not a valid submission',
                              text='That submission does not exist.<br />Please check the link and try again.'), 400
    elif submission.form_id != form.id:
        return render_template('error.html',
                              title='Not a valid submissions',
                              text='That submission does not match the form provided.<br />Please check the link and try again.'), 400
    else:
        DB.session.delete(submission)
        form.counter -= 1
        DB.session.add(form)
        DB.session.commit()
        flash('Submission successfully deleted', 'success')
        return redirect(url_for('form-submissions', hashid=hashid))
开发者ID:webscienceco,项目名称:formspree,代码行数:32,代码来源:views.py


示例5: form_submissions

def form_submissions(random_like_string):
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    form = Form.get_form_by_random_like_string(random_like_string)
    submissions = form.submissions

    if request_wants_json():
        if current_user.id != form.owner_id:
            return jsonerror(403, {'error': "You're not the owner of this form."})

        return jsonify({
            'submissions': [s.data for s in submissions]
        })
    else:
        if current_user.id != form.owner_id:
            return redirect(url_for('dashboard'))

        fields = set()
        for s in submissions:
            fields.update(s.data.keys())
        fields -= set(EXCLUDE_KEYS)

        return render_template('forms/submissions.html',
            form=form,
            fields=sorted(fields),
            submissions=submissions
        )
开发者ID:jean,项目名称:formspree,代码行数:28,代码来源:views.py


示例6: form_submissions

def form_submissions(hashid):
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    form = Form.get_with_hashid(hashid)

    if not form.controlled_by(current_user):
        if request_wants_json():
            return jsonerror(403, {'error': "You do not control this form."})
        else:
            return redirect(url_for('dashboard'))

    submissions = form.submissions

    if request_wants_json():
        return jsonify({
            'submissions': [s.data for s in submissions]
        })
    else:
        fields = set()
        for s in submissions:
            fields.update(s.data.keys())
        fields -= set(EXCLUDE_KEYS)

        return render_template('forms/submissions.html',
            form=form,
            fields=sorted(fields),
            submissions=submissions
        )
开发者ID:davidhegarty,项目名称:formspree,代码行数:29,代码来源:views.py


示例7: get

	def get(self):
		forms = Form.query().fetch(keys_only=True)		
		
		template_values = {
			'form_keys': map(lambda form: form.urlsafe(), forms)
		}
		
		html_template_path = os.path.join(templates_directory, 'admin_forms_list.html')
		html = template.render(html_template_path, template_values)
		
		self.response.write(html)
开发者ID:vanderkleij,项目名称:MailFacade,代码行数:11,代码来源:admin.py


示例8: form

def form(request, success_url='sent', template_name='contact_form.html'):

    notify = True
    contact_form = ContactForm()
    if request.method == 'POST':
        contact_form = ContactForm(request.POST, request.FILES)
        if contact_form.is_valid():
            new_form = {
                    'firstname': contact_form.cleaned_data['firstname'],
                    'lastname': contact_form.cleaned_data['lastname'],
                    'email': contact_form.cleaned_data['email'],
                    'pc': contact_form.cleaned_data['pc'],
                    'tipo': contact_form.cleaned_data['tipo'],
                    'caso': contact_form.cleaned_data['caso'],
                    }
            new_form = Form(**new_form)
            new_form.save(notify=notify)
            return HttpResponseRedirect(success_url)

    return render_to_response(template_name, RequestContext(request, {'form': contact_form}))
开发者ID:exezaid,项目名称:Hacklab,代码行数:20,代码来源:views.py


示例9: create

def create():
    form = ContactForm()
    if form.validate() is False:
        for error_type in form.errors:
            if form.errors[error_type][0] in dictionary():
                form.errors[error_type][0] = dictionary()[form.errors[error_type][0]]
        return render_template('contact/index.html', form=form, action=url_for('contact.create'))
    else:
        contact = Form()
        contact.name = form.name.data
        contact.email = form.email.data
        contact.subject = form.subject.data
        contact.message = form.message.data
        contact.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        message_tpl = render_template('contact/message_template.html', contact=contact)

        db.session.add(contact)
        db.session.commit()
        send_mail("Contato - DataViva", [admin_email], message_tpl)

        message = gettext("Your message has been sent successfully. We will soon get back to you.")
        flash(message, 'success')

        return redirect(url_for('contact.create'))
开发者ID:DataViva,项目名称:dataviva-site,代码行数:25,代码来源:views.py


示例10: forms

def forms():
    if request.method == 'GET':
        if request_wants_json():
            return jsonerror(501, {'error': "This endpoint may return the list of forms for the logged user."})
        else:
            return redirect(url_for('dashboard'))

    # Create a new form
    if not current_user.upgraded:
        return jsonerror(402, {'error': "Please upgrade your account."})

    if request.get_json():
        email = request.get_json().get('email')
    else:
        email = request.form.get('email')

    if not IS_VALID_EMAIL(email):
        if request_wants_json():
            return jsonerror(400, {'error': "The email you sent is not a valid email."})
        else:
            flash('The email you sent is not a valid email.', 'error')
            return redirect(url_for('dashboard'))

    form = Form(email, owner=current_user)
    DB.session.add(form)
    DB.session.commit()

    # A unique identifier for the form that maps to its id,
    # but doesn't seem like a sequential integer
    random_like_string = form.get_random_like_string()

    if request_wants_json():
        return jsonify({
            'ok': True,
            'random_like_string': random_like_string,
            'submission_url': settings.API_ROOT + '/' + random_like_string
        })
    else:
        return redirect(url_for('dashboard'))
开发者ID:jean,项目名称:formspree,代码行数:39,代码来源:views.py


示例11: handle

    def handle(self, sms):
        """Método chamado pelo RapidSMS para processar uma mensagem"""
        sub_type = Submission.TYPE_SMS  # estamos organizando as outras branchs do projeto
        answer = Config.get("message_unknown_format")

        if Submission.has_confirmation_pending(sms.connection.identity):
            submission = Submission.get_unconfirmed(sms.connection.identity)
            answer = submission.confirm(sms.text)
            return self.send_answer(sms, answer)

        if Form.main_form_exists():
            form = Form.get_main_form()

        else:
            keyword, separator, remaining_message = Form.extract_keyword(sms.text)
            sms.text = remaining_message
            form = Form.get_by_keyword_and_separator(keyword, separator)

        if form:
            answer = form.process_submission(sms, sub_type) or answer

        return self.send_answer(sms, answer)
开发者ID:institutotim,项目名称:resposta-rapida,代码行数:22,代码来源:app.py


示例12: get

 def get(self):
     formlist = []
     forms = Form.last()
     
     if forms:
         for form in forms:
             formlist.append(form.to_dict_key())
             
         self.response.headers['Content-Type'] = 'application/json'
         self.response.out.write(json.dumps(formlist))
         
     else:
         self.abort(404)
开发者ID:guillemborrell,项目名称:btdotnet,代码行数:13,代码来源:rest.py


示例13: confirm_email

def confirm_email(nonce):
    '''
    Confirmation emails point to this endpoint
    It either rejects the confirmation or
    flags associated email+host to be confirmed
    '''

    # get the form for this request
    form = Form.confirm(nonce)

    if not form:
        return render_template('error.html',
                               title='Not a valid link',
                               text='Confirmation token not found.<br />Please check the link and try again.'), 400

    else:
        return render_template('forms/email_confirmed.html', email=form.email, host=form.host)
开发者ID:mgraupner,项目名称:formspree,代码行数:17,代码来源:views.py


示例14: form_recaptcha_toggle

def form_recaptcha_toggle(hashid):
    form = Form.get_with_hashid(hashid)

    if not valid_domain_request(request):
        return jsonify(error='The request you made is not valid.<br />Please visit your dashboard and try again.'), 400

    if form.owner_id != current_user.id and form not in current_user.forms:
        return jsonify(error='You aren\'t the owner of that form.<br />Please log in as the form owner and try again.'), 400

    if not form:
        return jsonify(error='That form does not exist. Please check the link and try again.'), 400
    else:
        form.captcha_disabled = not form.captcha_disabled
        DB.session.add(form)
        DB.session.commit()

        if form.captcha_disabled:
            return jsonify(disabled=True, message='CAPTCHA successfully disabled')
        else:
            return jsonify(disabled=False, message='CAPTCHA successfully enabled')
开发者ID:davidcretu,项目名称:formspree,代码行数:20,代码来源:views.py


示例15: admin

def admin(request):
    user = users.get_current_user()
    if not (user and users.is_current_user_admin()):
        return HttpResponseRedirect(users.create_login_url('/admin'))

    if request.method == 'POST' and request.POST['id'] and request.POST['action']:
        id = request.POST['id']
        action = int(request.POST['action'])
        model = Form.get(id)

        model.status = action
        model.put()

    pending = []
    accepted = []
    rejected = []
    
    for x in db.GqlQuery("SELECT * FROM poznanopen_form"):
        { 1:pending, 2: accepted, 3: rejected }[x.status].append(x)

    return render_to_response('admin.html', {'page': 'admin', 'pending': pending, 'accepted': accepted, 'rejected': rejected})
开发者ID:MHordecki,项目名称:poznanopen,代码行数:21,代码来源:views.py


示例16: create

def create():
    form = ContactForm()
    if form.validate() is False:
        return Response(status=400, mimetype='application/json')
    else:
        contact = Form()
        contact.name = form.name.data
        contact.email = form.email.data
        contact.subject = form.subject.data
        contact.message = form.message.data
        contact.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        message_tpl = render_template(
            'contact/message_template.html', contact=contact)

        db.session.add(contact)
        db.session.commit()
        send_mail("Mensagem recebida via página de Contato",
                  ["[email protected]"], message_tpl)

        message = gettext(
            "Your message has been sent successfully. We will soon get back to you.")

        return Response(message, status=200, mimetype='application/json')
开发者ID:jaotta,项目名称:dataviva-site,代码行数:24,代码来源:views.py


示例17: registration

def registration(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            model = Form()
            model.fullname = data['fullname']
            model.wcaid = data['wcaid']
            model.country = data['country']
            model.city = data['city']
            model.email = data['email']
            model.tshirt = data['tshirt']
            model.nick = data['nick']
            model.accomodation = data['accomodation']
            model.born = datetime.date(int(data['bornyear']), int(data['bornmonth']), int(data['bornday']))
            model.events = [str(ev) for ev in data if ev.startswith('ev_') and data[ev] == True]
            model.status = 1
            model.put()

            return HttpResponseRedirect('/thanks')
    else:
        form = RegistrationForm()

    return render_to_response('registration.html', {
        'form': form,
        'page': 'registration',
        'years': range(1900, 2009),
        'months': range(1, 13),
        'days': range(1, 32),
        })
开发者ID:MHordecki,项目名称:poznanopen,代码行数:30,代码来源:views.py


示例18: get_context_data

 def get_context_data(self, *args, **kwargs):
     return {
         'KIND_CHOICES': Field.KIND_CHOICES,
         'form': Form.get_by_name(kwargs['name']),
     }
开发者ID:jpic,项目名称:zodb-admin,代码行数:5,代码来源:views.py


示例19: create_form

def create_form():
    # create a new form

    if not current_user.upgraded:
        g.log.info('Failed to create form from dashboard. User is not upgraded.')
        return jsonerror(402, {'error': "Please upgrade your account."})

    if request.get_json():
        email = request.get_json().get('email')
        url = request.get_json().get('url')
        sitewide = request.get_json().get('sitewide')
    else:
        email = request.form.get('email')
        url = request.form.get('url')
        sitewide = request.form.get('sitewide')

    g.log = g.log.bind(email=email, url=url, sitewide=sitewide)

    if not IS_VALID_EMAIL(email):
        g.log.info('Failed to create form from dashboard. Invalid address.')
        if request_wants_json():
            return jsonerror(400, {'error': "The provided email address is not valid."})
        else:
            flash('The provided email address is not valid.', 'error')
            return redirect(url_for('dashboard'))

    g.log.info('Creating a new form from the dashboard.')

    email = email.lower() # case-insensitive
    form = Form(email, owner=current_user)
    if url:
        url = 'http://' + url if not url.startswith('http') else url
        form.host = referrer_to_path(url)

        # sitewide forms, verified with a file at the root of the target domain
        if sitewide:
            if sitewide_file_check(url, email):
                form.host = remove_www(referrer_to_path(urljoin(url, '/'))[:-1])
                form.sitewide = True
            else:
                return jsonerror(403, {'error': "Couldn't verify the file at %s." % url})

    DB.session.add(form)
    DB.session.commit()

    if form.host:
        # when the email and url are provided, we can automatically confirm the form
        # but only if the email is registered for this account
        for email in current_user.emails:
            if email.address == form.email:
                g.log.info('No need for email confirmation.')
                form.confirmed = True
                DB.session.add(form)
                DB.session.commit()
                break
        else:
            # in case the email isn't registered for this user
            # we automatically send the email confirmation
            form.send_confirmation()

    if request_wants_json():
        return jsonify({
            'ok': True,
            'hashid': form.hashid,
            'submission_url': settings.API_ROOT + '/' + form.hashid,
            'confirmed': form.confirmed
        })
    else:
        flash('Your new form endpoint was created!', 'success')
        return redirect(url_for('dashboard', new=form.hashid) + '#form-' + form.hashid)
开发者ID:webscienceco,项目名称:formspree,代码行数:70,代码来源:views.py


示例20: send

def send(email_or_string):
    '''
    Main endpoint, finds or creates the form row from the database,
    checks validity and state of the form and sends either form data
    or verification to email.
    '''

    g.log = g.log.bind(target=email_or_string)

    if request.method == 'GET':
        if request_wants_json():
            return jsonerror(405, {'error': "Please submit POST request."})
        else:
            return render_template('info.html',
                                   title='Form should POST',
                                   text='Make sure your form has the <span class="code"><strong>method="POST"</strong></span> attribute'), 405

    host = referrer_to_path(request.referrer)
    if not host:
        if request_wants_json():
            return jsonerror(400, {'error': "Invalid \"Referrer\" header"})
        else:
            return render_template('error.html',
                                   title='Unable to submit form',
                                   text='<p>Make sure you open this page through a web server, Formspree will not work in pages browsed as HTML files. Also make sure that you\'re posting to <b>https://</b>{host}.</p><p>For geeks: could not find the "Referrer" header.</p>'.format(host=request.url.split('//')[1])), 400

    g.log = g.log.bind(host=host, wants='json' if request_wants_json() else 'html')

    g.log.info('Received submission.')
    if not IS_VALID_EMAIL(email_or_string):
        # in this case it can be a hashid identifying a
        # form generated from the dashboard
        hashid = email_or_string
        form = Form.get_with_hashid(hashid)

        if form:
            if form.disabled:
                # owner has disabled the form, so it should not receive any submissions
                if request_wants_json():
                    return jsonerror(403, {'error': 'Form not active'})
                else:
                    return render_template('error.html',
                                           title='Form not active',
                                           text='The owner of this form has disabled this form and it is no longer accepting submissions. Your submissions was not accepted'), 403
            email = form.email

            if not form.host:
                # add the host to the form
                form.host = host
                DB.session.add(form)
                DB.session.commit()

                # it is an error when
                #   form is sitewide, but submission came from a host rooted somewhere else, or
                #   form is not sitewide, and submission came from a different host
            elif (not form.sitewide and form.host != host) or (
                   form.sitewide and (
                     not host.startswith(form.host) and \
                     not remove_www(host).startswith(form.host)
                   )
                 ):
                g.log.info('Submission rejected. From a different host than confirmed.')
                if request_wants_json():
                    return jsonerror(403, {
                       'error': "Submission from different host than confirmed",
                       'submitted': host, 'confirmed': form.host
                    })
                else:
                    return render_template('error.html',
                                           title='Check form address',
                                           text='This submission came from "%s" but the form was\
                                                 confirmed for address "%s"' % (host, form.host)), 403
        else:
            # no form row found. it is an error.
            g.log.info('Submission rejected. No form found for this target.')
            if request_wants_json():
                return jsonerror(400, {'error': "Invalid email address"})
            else:
                return render_template('error.html',
                                       title='Check email address',
                                       text='Email address %s is not formatted correctly' \
                                            % str(email_or_string)), 400
    else:
        # in this case, it is a normal email
        email = email_or_string.lower()

        # get the form for this request
        form = Form.query.filter_by(hash=HASH(email, host)).first() \
               or Form(email, host) # or create it if it doesn't exists
        if form.disabled:
            g.log.info('submission rejected. Form is disabled.')
            if request_wants_json():
                return jsonerror(403, {'error': 'Form not active'})
            else:
                return render_template('error.html',
                                       title='Form not active',
                                       text='The owner of this form has disabled this form and it is no longer accepting submissions. Your submissions was not accepted'), 403

    # If form exists and is confirmed, send email
    # otherwise send a confirmation email
#.........这里部分代码省略.........
开发者ID:webscienceco,项目名称:formspree,代码行数:101,代码来源:views.py



注:本文中的models.Form类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Game类代码示例发布时间:2022-05-27
下一篇:
Python models.Folder类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap