Example #1
0
def register():
    form = MyForm()
    if form.validate_on_submit():
        # cur  = mysql.connection.cursor()
        # cur.execute("INSERT INTO kaskoghar(username,email,password,name) VALUES(%s,%s,%s,%s)",(form.username.data,form.email.data,form.password.data,form.name.data))
        # mysql.connection.commit()
        # cur.close()
        db.session.close()
        x = db.session.query(KaskoGhar).filter_by(
            username=form.username.data).first()
        if (x):
            flash('choose a different username ')
            return render_template('registration.html', form=form)
        formdata = KaskoGhar(username=form.username.data,
                             email=form.email.data,
                             password=generate_password_hash(
                                 form.password.data),
                             name=form.name.data)
        print(type(formdata))
        db.session.add(formdata)

        db.session.commit()
        print(db.session)
        return redirect(url_for('home'))
    return render_template('registration.html', form=form)
Example #2
0
def profile():
    form = MyForm()
    print form.validate_on_submit()
    print form.errors
    print request.form
    if request.method == 'POST' and form.validate_on_submit():
        count = db.session.query(UserProfile).count()
        location = form.location.data
        bio = form.biography.data
        lname = form.lastname.data
        fname = form.firstname.data
        mail = form.email.data
        gender = form.gender.data
        photograph = form.photo.data
        date = datetime.date.today()
        uid = 10000 + count
        filename = str(uid) + ".jpg"
        photograph.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        user = UserProfile(id=uid,
                           first_name=fname,
                           last_name=lname,
                           gender=gender,
                           location=location,
                           bio=bio,
                           email=mail,
                           created_on=date)
        db.session.add(user)
        db.session.commit()
        flash('Profile created!', 'success')
        return redirect(url_for('profiles'))
    else:
        return render_template('profile.html', form=form)
Example #3
0
def results():
    """ Show results page or the error page """
    myform = MyForm(request.form)
    if request.method == 'POST' and myform.validate():
        dub = myform.doubler.data * 2
        return render_template('results.html', form=myform, doubler=dub)
    return render_template('errors.html', form=myform)
Example #4
0
def home_view(request, *args, **kwargs):
    today = datetime.datetime.now().date()

    if request.method == 'POST':
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():
            action = request.POST['action']
            title = str(request.FILES['field'])
            content = request.FILES['field'].read()
            f = open(str(settings.MEDIA_ROOT) + title, "wb")
            f.write(content)
            f.close()
            loadInputAndProcess('media/' + title, action == 'watch')
            if action == 'watch':
                return render(request, "myaction.html", {
                    'value': "output.mp4",
                    'annotate': 'false'
                })
            elif action == 'annotate':
                return render(request, "myaction.html", {
                    'value': title,
                    'annotate': 'true'
                })
            else:
                return render(request, "showlink.html",
                              {'value': "output.avi"})

    form = MyForm()
    print(form)
    return render(request, "home.html", {"today": today, 'form': form})
Example #5
0
def index():

    bitcoind = bitcoinrpc.connect_to_local()
    balance = bitcoind.getbalance('')
    if balance < Decimal('2'):
        return render_template("base.html", balance=False)

    if request.method == 'GET':
        form = MyForm()

    elif request.method == 'POST':

        form = MyForm(request.form)
        if form.validate():
            
            result, amount = send_to_address(form.data.get("address"))
            
            add_transaction_to_database(form.data.get("address"), float(amount), request.remote_addr, result)
            return render_template('success.html', result=result, amount=amount)

    template_data = {
        "form": form,
        "balance": True,
    }

    return render_template("base.html", **template_data)
Example #6
0
def profile():
    myform = MyForm()

    if request.method == 'POST':
        if myform.validate_on_submit():

            firstname = myform.firstname.data
            lastname = myform.lastname.data
            email = myform.email.data
            location = myform.location.data
            biography = myform.biography.data
            gender = myform.gender.data
            photo = myform.photo.data

            filename = secure_filename(photo.filename)
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            userid = str(uuid.uuid4())
            created_on = format_date_joined()

            db = connect_db()
            cur = db.cursor()
            query = "insert into Profiles (firstname, lastname, email, location, biography, gender, photo, userid, created_on) values (%s, %s, %s, %s, %s, %s, %s, %s, %s);"
            data = (firstname, lastname, email, location, biography, gender,
                    filename, userid, created_on)
            cur.execute(query, data)
            db.commit()

            flash('Profile successfully added!', 'success')
            return redirect(url_for("profiles"))

        flash_errors(myform)
    return render_template('profile.html', form=myform)
Example #7
0
def login():
    tkn = ''
    try:
        AXS_TOKEN = session.get('oauth_token')
        AXS_TOKEN_SECRET = session.get('oauth_token_secret')
        VERIF = request.args.get('oauth_verifier', '')
        tkn = CLIENT.get_access_token(AXS_TOKEN, AXS_TOKEN_SECRET, VERIF) # this is the tkn we need to save!
        session['tkn'] = tkn
    except (KeyError, ValueError):
        pass
    if not tkn:
        tkn = session.get('tkn')
    try:
        note_store = CLIENT.get_note_store()
    except TypeError:
        global CLIENT
        CLIENT = get_evernote_client(tkn)

    form = MyForm()
    if form.validate_on_submit():
        new = User(form.data['email'], session.get('tkn'))
        db.session.add(new)
        db.session.commit()
        # need to stop people from adding the same username
        return redirect(url_for('.success'))
    return render_template('authorized.html', form=form)
Example #8
0
def plan(request, location):
    context_dict ={}
     # A HTTP POST?
    if request.method == 'POST':
        form = MyForm(request.POST)
        planner = Planner.objects.get(user=request.user)
        tripForm = CreateTrip(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid() and tripForm.is_valid():
            # Save the new category to the database.
            trip = tripForm.save(commit=False)
            trip.planner=planner #Planner will be sent automatically eventually
            trip.save()
            data = form.cleaned_data['places']
            for place in data:
                visit = Visit(trip=trip, place=place)
                visit.save()
            # The user will be shown the summary page.
            return redirect(reverse('tripSummary', args=[trip.id] ))
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
            context_dict['errors'] = form.errors
    else:
        places = get_places(location)
        form = CreateTrip()
        # If the request was not a POST, display the form to enter details.
        context_dict['places'] = places
        context_dict['tripForm'] = form

    return render(request, 'plan.html', context_dict)
Example #9
0
def contact():
    form = MyForm()
    if form.validate_on_submit():
        return "Hey there, {}!".format(form.name.data)
        
    else:
        return render_template("contact.html", form=form)
Example #10
0
def put_applicant():

    global job_id

    if request.method == 'POST':
        if request.get_json():

            job_data = request.get_json()
            job_id = job_data['id']

            return jsonify({"message": "success"})

    form = MyForm()

    form.validate_on_submit()
    for key, value in form.errors.items():
        flash(value, 'error')

        # if action is POST and form is valid
    if form.validate_on_submit():

        result = request.form.to_dict()
        data = {
            'firstname': result['firstname'],
            'surname': result['surname'],
            'email': result['email'],
            'dob': result['dob'],
            'phone': result['phone'],
            'job_ref': job_id[3:]
        }
        if client:
            # for reading the job_ref
            job_data = request.get_json()
            flag = False
            # check whether in the database there is no user with these credentials
            # an user CANNOT apply for the same job once but CAN apply two different jobs
            for document in appi_db:
                if (document['email']
                        == data['email']) and (job_id[3:]
                                               == document['job_ref']):
                    flag = True

            if flag == False:
                # create a document and add the data to it
                my_document = appi_db.create_document(data)

                flash('You have been added to the database', 'success')
                # use sessions to share the document info to the other routes
                session['document'] = my_document
            else:
                flash('Sorry you cannot apply for the same job twice',
                      'validation')

            return render_template('applicant.html', form=form)
        else:
            print('No database')
            return jsonify(data)

    return render_template('applicant.html', form=form)
Example #11
0
def home():
    form = MyForm()

    if form.validate_on_submit():
        date = form.date.data
        city = form.city.data

    return render_template("login.html", title='Prometric check', form=form)
Example #12
0
def submit():
    form = MyForm()
    if form.validate_on_submit():
        name = form.name.data
        print name
        store_bookmark(name, name)
        return 'success data'
    return render_template('submit.html', form=form)
Example #13
0
def signup():
    if current_user.is_authenticated:
        return redirect(url_for('dashboard'))

    form = MyForm()
    if request.method == "POST" and form.validate_on_submit():
        # referral = request.form.get('ref')
        email = form.email.data
        password = form.password.data
        username = form.username.data
        bank_name = form.bank_name.data
        account_name = form.account_name.data
        account_number = form.account_number.data
        bitcoin_wallet = form.bitcoin_wallet.data
        mobile_number = form.mobile_number.data
        country = request.form.get("country")
        referral = form.referral.data

        password = md5_crypt.hash(password)
        check_for_first_user = len(User.query.all())
        if not check_for_first_user:
            user = User(username=username,
                        referral=referral,
                        is_admin=True,
                        password=password,
                        country=country,
                        account_number=account_number,
                        account_name=account_name,
                        bitcoin_addr=bitcoin_wallet,
                        bank_name=bank_name,
                        mobile_number=mobile_number,
                        email=email)
        else:
            user = User(username=username,
                        referral=referral,
                        is_admin=False,
                        password=password,
                        country=country,
                        account_number=account_number,
                        account_name=account_name,
                        bitcoin_addr=bitcoin_wallet,
                        bank_name=bank_name,
                        mobile_number=mobile_number,
                        email=email)

        db.session.add(user)
        db.session.commit()

        flash("You have signed up successfully")
        return redirect('/login')
    else:
        ref = request.args.get("ref")
        context = {"ref": ref}
        all_tasks = Admin_tasks.query.all()
        for task in all_tasks:
            context[f"{task.key}"] = task.value
        return render_template("sign_up.html", form=form, context=context)
Example #14
0
    def post(self, request):
        form = MyForm(data=request.POST)
        if form.is_valid():
            messages.success(request, form.cleaned_data['message'])
        else:
            messages.error(request, 'Validation failed')

        c = {'form': form}
        return render(request, 'my_app/form.html', c)
Example #15
0
def contact():
    myform=MyForm()
    """Render the website's contact page."""
    if request.method == 'POST' and myform.validate_on_submit():
        send_mail(myform.name.data,myform.email.data,myform.subject.data,myform.message.data)
        flash('Message Successfully Sent')
        return redirect(url_for('home'))
    else:
        return render_template('contact.html',form=myform,addtext='Error sending')
Example #16
0
def contact():
    form = MyForm()
    if form.validate_on_submit():
        msg	=	Messagere)
        msg.body =	request.form['message']
        mail.send(msg)
        
        return redirect(url_for('home'))
            
    return render_template('contact.html', form=form)
def index():
    form = MyForm()
    # post
    if form.validate_on_submit():
      # extract form input data
      input_value = form.name.data
      result = input_value.upper()
      return render_template('result.html', result=result)
    # get
    return render_template('index.html', form=form)
def contact():
    form = MyForm()
    if form.validate_on_submit():
        msg	= Message(request.form['subject'], sender=(request.form['name'], request.form['email']), recipients=["*****@*****.**"])
        msg.body =	request.form['message']
        mail.send(msg)
        msg.body	=	request'This	is	the	body	of	the	message'
        return redirect(url_for('home'))
            
    return render_template('contact.html', form=form)
Example #19
0
def contact():
    form = MyForm(request.form)
    if request.method == 'POST' and form.validate():
        msg = Message("form.subject.data",
                      sender=('form.name.data', 'form.email.data'),
                      recipients=['smtp.mailtrap.io'])
        msg.body = 'form.textArea.data'
        mail.send(msg)
        flash('Message Sent')
        return redirect(url_for('home'))
    return render_template('contact.html')
Example #20
0
def contact():
    form = MyForm()
    if request.method == 'POST':
        if form.validate():
            msg =  Message(request.form['subject'],
                    sender=(request.form['name'],request.form['email']),
                    recipients=["*****@*****.**"])
            msg.body = request.form['message'];
            mail.send(msg)
            flash('Message was sent')
            return redirect(url_for('home'))
    return render_template('contact.html',form=form)
Example #21
0
def contact():
    form = MyForm()
    if request.method == "POST":
        if form.validate_on_submit():
            msg = Message("subject",
                          sender=("name", "email"),
                          recipients=["*****@*****.**"])
            msg.body = 'message'
            mail.send(msg)
            flash('message has been sent!!', 'success')
            return redirect(url_for('home'))
    return render_template('contact.html', form=form)
def contact():
    form = MyForm()
    if form.validate_on_submit():
        msg = Message(request.form['subject'],
                      sender=(request.form['name'], request.form['email']),
                      recipients=["*****@*****.**"])
        msg.body = request.form['message']
        mail.send(msg)

        return redirect(url_for('home'))

        return redirect(url_for('home'))
Example #23
0
def contact():
    form = MyForm()
    if form.validate_on_submit():
        msg = Message(request.form['subject'],
                      sender=(request.form['name'], request.form['email']),
                      recipients=["*****@*****.**"])
        msg.body = request.form['message']
        mail.send(msg)

        return redirect(url_for('home'))
        flash('Mail Sent!')
        return str(get_flashed_messages())

    return render_template('contact.html', form=form)
Example #24
0
    def get_dynamic_form(self, dict):
        """
        for eg- get_dynamic_form() called with argument dict={u't1': {'priority': u'1', 'field_type': 'textfield', 'mandatory': 1}}
        This will return a form with a t1 labelled textfield which is mandatory and row priority is 1
        """

        form = MyForm()
        for label, field_data in dict.items():
            print field_data
            if field_data["field_type"] == "textfield":
                form.fields[label] = self.get_text_field(label, field_data["mandatory"])
            if field_data["field_type"] == "integerfield":
                form.fields[label] = self.get_integer_field(label, field_data["mandatory"])
            if field_data["field_type"] == "choicefield":
                form.fields[label] = self.get_choice_field(label, field_data["options"], field_data["mandatory"])
            if field_data["field_type"] == "radio":
                form.fields[label] = self.get_radio_field(label, field_data["options"], field_data["mandatory"])
            if field_data["field_type"] == "checkbox":
                form.fields[label] = self.get_checkbox(label, field_data["options"], field_data["mandatory"])
            if field_data["field_type"] == "textbox":
                form.fields[label] = self.get_textbox(label, field_data["mandatory"])
            if field_data["field_type"] == "decimalfield":
                form.fields[label] = self.get_decimal_field(label, field_data["options"], field_data["mandatory"])
            form.fields[label].priority = field_data["priority"]
        return form
Example #25
0
def form_creation(request):
    if request.user.is_authenticated():
        pst = request.POST
        form = MyForm(pst)
        if not form.is_valid():
            return render(request, 'create_form/create_form_template.html')
        event_id = map_form_to_database(form.cleaned_data, request.user)
        if event_id is not None:
            context = {"event_id": event_id}
            return render(request, 'create_form/form_created.html', context)
        else:
            return HttpResponseRedirect('/')
    else:
        return render(request, 'unauthorized_template.html')
def contact():
    """ """
    form = MyForm(request.form)
    if request.method=="POST" and form.validate():
        name=request.form['name']
        email=request.form['email']
        subject=request.form['subject']
        message=request.form['message']
        
        msg = Message(subject, sender=(name,email), recipients = ["*****@*****.**"])
        msg.body = message
        mail.send(msg)
        flash('Message sent successfully',)
        return redirect(url_for('home'))
Example #27
0
def home():
    message = ''
    form = MyForm(csrf_enabled=False)
    if form.validate_on_submit():
        message = form.message.data
    else:
        message_validation_errors = form.errors.get('message')
        if message_validation_errors:
            message = message_validation_errors[0]  # 今回は0番目のエラーのみ表示する

    return render_template(
        'index.html',
        message=message,
        form=form,
    )
Example #28
0
def contact():
    form = MyForm()
    if request.method=='POST':
        if form.validate_on_submit():
            name = form.name.data
            email = form.email.data
            subject = request.form['subject']
            message = request.form['message']
            msg = Message(subject, sender=(name,email), recipients=["*****@*****.**"])
            msg.body = message
            mail.send(msg)
            flash('Message Sent')
            return redirect(url_for('home'))

    return render_template('contact.html', form=form)
Example #29
0
def get_atis(icao):
    print(icao)
    form = MyForm()
    if form.is_submitted:
        print("Validated")
        return render_template("get_atis.html", icao=icao)
    return render_template("get_atis.html")
Example #30
0
def contact():
    form = MyForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            msg = Message(form.subject.data,
                          sender=(form.name.data, form.email.data),
                          recipients=["*****@*****.**"])
            msg.body = form.message.data
            mail.send(msg)
            flash('email successfully sent')
            return redirect('/')
        else:
            flash('error: sending of email failed')
            return redirect('/contact')
    else:
        return render_template('contact.html', form=form)
Example #31
0
def predict():
    '''
    For rendering results on HTML GUI
    '''
    form = MyForm()

    features = request.form.values()

    final_features = []
    for val in features:

        final_features.append(val)
    final_features.remove(final_features[-1])
    final_features.remove(final_features[0])
    final_list = []
    for num in final_features:
        final_list.append(int(num))
    final = [final_list]
    final_arr = np.asarray(final)
    final_arr.reshape(-1, 1)
    prediction = model.predict(final_arr)

    output = prediction
    if (output == 0):
        predicted_value = "Rejected"
    elif (output == 1):
        predicted_value = "Accepted"

    #output=features
    return render_template(
        'about.html',
        prediction_text=
        f"Your Loan Application is likely to be : {predicted_value}")
def predict():
    form = MyForm(request.form)
    message = ''
    liste = []

    if request.method == 'POST':

        liste.append(form.Attr16.data)
        liste.append(form.Attr25.data)
        liste.append(form.Attr33.data)
        liste.append(form.Attr40.data)
        liste.append(form.Attr46.data)
        liste.append(form.Attr63.data)
        liste.append(form.year.data)
        p = model.predict(pd.DataFrame(liste))[0]
        if p == 1:
            message = "Sorry it seems that your company go straight to bankruptcy"
        elif p == 0:
            message = "Your company will not go to bankruptcy"

        flash(message)
        return redirect(url_for('index'))
    else:

        return render_template('pred.html', form=form)
Example #33
0
def contact():
    form = MyForm()
    if request.method == "POST":
        if form.validate_on_submit():
            msg = Message(form.subject.data,
                          sender=(form.name.data, form.email.data),
                          recipients=["*****@*****.**"])
            msg.body = form.message.data
            #msg=Message(request.form['subject'], sender=(request.form['name'], request.form['email']), recipients=['smtp.mailtrap.io'])
            #msg.body=request.form['message']
            mail.send(msg)
            flash("Message successfully sent!")
            return redirect('/')
        else:
            return redirect('/contact')

    return render_template('contact.html', form=form)
Example #34
0
def contact():
    """ """
    form = MyForm(request.form)
    if request.method == "POST" and form.validate():
        name = request.form['name']
        email = request.form['email']
        subject = request.form['subject']
        message = request.form['message']

        msg = Message(subject,
                      sender=(name, email),
                      recipients=["*****@*****.**"])
        msg.body = message
        mail.send(msg)
        flash('Message sent successfully', 'success')
        return redirect(url_for('home'))
    return render_template('contact.html', form=form)
Example #35
0
def contact():
    """Render the website's contact page."""
    contactForm = MyForm()
    if request.method == "POST":
        if contactForm.validate_on_submit():
            name = contactForm.name.data
            email = contactForm.email.data
            subject = contactForm.subject.data
            message = contactForm.message.data
            msg = Message(subject,
                          sender=(name, email),
                          recipients=["*****@*****.**"])
            msg.body = message
            mail.send(msg)
            flash('Message sent successfully', 'success')
            return redirect(url_for("home"))
    return render_template('contact.html', form=contactForm)
Example #36
0
def generatedReport(request):
    if request.method == "POST":
        f = MyForm(request.POST, request.FILES)
        if f.is_valid():
            search = f.cleaned_data["Search"]
            sign = f.cleaned_data["Name"]
            response = HttpResponse(content_type="application/pdf")
            response["Content-Disposition"] = 'attachment; filename="somefilename.pdf"'

            buffer = BytesIO()

            model = Profile
            headers = []
            for field in model._meta.fields:
                headers.append(field.name)

            p = canvas.Canvas(buffer)
            p.setLineWidth(0.3)
            p.setFont("Helvetica", 12)

            line = 0
            for obj in Profile.objects.all():
                line += 1
                string = ""
                for field in headers:
                    if field == "name":
                        val = getattr(obj, field)
                        if type(val) == unicode:
                            val = val.encode("utf-8")
                        if (
                            ((val <= search) and (int(sign) == 1))
                            or ((val == (search)) and (int(sign) == 2))
                            or ((val >= (search)) and (int(sign) == 3))
                        ):
                            string = string + " " + str(val)
            p.drawString(30, 800 - 50 * line, string)

            # Close the PDF object cleanly, and we're done.
            p.showPage()
            p.save()

            pdf = buffer.getvalue()
            buffer.close()
            response.write(pdf)
            return response
Example #37
0
def submit():
    """Submits form data to cloudforest"""
    form = MyForm(request.form, csrf_enabled=False)
    if form.validate_on_submit():
        # I think what we want to do here is spawn off the cloudforest into its
        # own subprocess. It sort of works for now.

        # ===========================
        #  COMMENT OUT LINES 88-90 UNLESS
        #  YOU WANT TO INSTALL A BUNCH
        #  OF PYTHON SCIENTIFIC DEPENDANCIES

        p = Process(target=run_cloudforest(form.data))
        p.start()
        p.join()

        pass  # don't comment out the pass or the if statement becomes invalid

    return render_template("index.html", form=form)
Example #38
0
def create_account():
	form = MyForm()
	invitation_no = app.config['INVITATION']
	if form.validate_on_submit():
		user = User(
			email = form.email.data,
			username = form.name.data,
			password = form.password.data,			
		)
		#验证邀请码
		invitation = form.invitation.data
		if invitation == invitation_no:
			db.session.add(user)
			db.session.commit()
			return redirect('/')
		else:
			return redirect('/404')

	return render_template('accounts/create.html', form=form)
Example #39
0
def index():
    #form = MyForm(LANGUAGES=['ru',])
    form = MyForm()
    if form.validate_on_submit():
        # template (file.rml) + data (dict) | jinja (render_template) | trml2pdf(str): str | respose
        # retvalue = render_template
        # make_response
        # add content type
        # TODO: rml template as pre-loaded string
        # 1. prepare data
        #d = __tune_data(form)
        # 2. mk rml
        #rml = render_template('uvedomlenie.rml', d = d)  # str RML(str filename, dict dict)
        # 3. mk pdf
        #pdf = trml2pdf.parseString(rml) # str
        # 4. get out
        #rsp = Response(response=pdf, mimetype='application/pdf', content_type='application/pdf')
        #return rsp
        return Response(response=trml2pdf.parseString(render_template('uvedomlenie.rml', d = __tune_data(form))), mimetype='application/pdf', content_type='application/pdf')
    return render_template('index.html', form = form)
def submit(request):
    if is_student(request):
        if request.method == "POST":
            try:
                a = request.FILES['pdf']
            except:
                return HttpResponse("Please select a file")
            f = MyForm(request.POST,request.FILES)
            if f.is_valid():
                try:
                    valid_file = f.clean_content()
                except ValidationError as e:
                    return HttpResponse(e.message)

                assignment = Assignment.objects.get(id=int(request.POST['id']))
                try:
                    sub = Submission.objects.get(user = request.user,
                                           assignment = assignment
                                            )
                    sub.is_checked = False
                    if assignment.deadline.microsecond < datetime.now().microsecond:
                        sub.is_late = True
                    sub.save()
                except:
                    sub = Submission.objects.create(user=request.user,
                                                    assignment=assignment
                                                    )
                    if assignment.deadline.microsecond < datetime.now().microsecond:
                        sub.is_late = True
                        sub.save()
                with open(join(settings.BASE_DIR ,'Uploads/'+str(request.user.id))+'/'+str(request.POST['id'])+'.pdf', 'wb+') as destination:
                    for chunk in valid_file.chunks():
                        destination.write(chunk)
            else:
                return HttpResponse("Select a file")

        return student_home(request)
    elif is_teacher(request):
        return teacher_home(request)
    return render(request,"home.html")