コード例 #1
0
ファイル: routes.py プロジェクト: nysamnang/simple-crud-flask
def update_student(student_id):
    form = UpdateForm()
    student = Student.query.filter_by(student_id=student_id).first_or_404()
    if form.validate_on_submit():

        student.student_id = student_id,
        student.first_name_en = form.first_name_en.data,
        student.last_name_en = form.last_name_en.data,
        student.first_name_kh = form.first_name_kh.data,
        student.last_name_kh = form.last_name_kh.data,
        student.gender = form.gender.data,
        student.date_of_birth = form.date_of_birth.data,
        student.phone = form.phone.data,
        student.email = form.email.data,
        student.address = form.address.data

        db.session.commit()
        flash('Your changes have been saved.', category='success')
        return redirect(url_for('index', option='active'))
    elif request.method == 'GET':
        form.student_id.data = student.student_id
        form.first_name_en.data = student.first_name_en
        form.last_name_en.data = student.last_name_en
        form.first_name_kh.data = student.first_name_kh
        form.last_name_kh.data = student.last_name_kh
        form.gender.data = student.gender
        form.date_of_birth.data = student.date_of_birth
        form.phone.data = student.phone
        form.email.data = student.email
        form.address.data = student.address

    return render_template('update_student.html', form=form)
コード例 #2
0
def updateImp():
    form = UpdateForm(request.form)
    idnumNew = session['idnumNew']
    if request.method == 'POST':
        fnameNew = form.fnameNew.data
        mnameNew = form.mnameNew.data
        lnameNew = form.lnameNew.data
        sexNew = form.sexNew.data
        courseidNew = form.courseidNew.data


        if form.validate():
            update(idnumNew,fnameNew,mnameNew,lnameNew,sexNew,courseidNew)
            flash('Successfully Updated', 'success')
            return render_template("update.html", form = form)
        elif not form.validate():
                flash('Please fill up each of the following', 'error')
                return render_template("update.html", form = form)

        else:
            flash('error in update operation', 'error')
            return render_template("updateGet.html", form=form)


    else:
        return render_template("update.html", form=form)
コード例 #3
0
def edit_pattern(pattern_id):
    """
    Form to edit a pattern in particular
    """
    try:
        the_pattern = get_pattern(mongo.db, pattern_id)
        form = UpdateForm(mongo.db)

        # Set default values
        form.category_name.default = the_pattern['category_name']
        form.pattern_language.default = the_pattern['pattern_language']
        form.pattern_name.default = the_pattern['pattern_name']
        form.pattern_by.default = the_pattern['pattern_by']
        form.pattern_needle_size.default = the_pattern['pattern_needle_size']
        form.pattern_gauge.default = the_pattern['pattern_gauge']
        form.pattern_yarn_weight.default = the_pattern['pattern_yarn_weight']
        form.pattern_yardage.default = the_pattern['pattern_yardage']
        form.pattern_size.default = the_pattern['pattern_size']
        form.pattern_difficulty.default = the_pattern['pattern_difficulty']
        form.pattern_url.default = the_pattern['pattern_url']
        form.pattern_img.default = the_pattern['pattern_img']
        form.pattern_notes.default = the_pattern['pattern_notes']
        form.process()

        return render_template(
            'addpattern.html',
            form=form,
            isNew=False,
            id=pattern_id
        )

    except Exception:
        return render_template('404.html')
コード例 #4
0
def update_info(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = UpdateForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            sender = form.cleaned_data['sender']
            cc_myself = form.cleaned_data['cc_myself']

            recipients = ['*****@*****.**'] #TODO Change to Claudia's email
            if cc_myself:
                recipients.append(sender)

            send_mail(subject, message, sender, recipients)
            return HttpResponseRedirect('/thanks/')
    # if a GET (or any other method) we'll create a blank form
    else:
        form = UpdateForm()

    f = EmployeeFilter(request.GET, queryset=Employee.objects.all())
    table = EmployeeTable(f.qs)
    RequestConfig(request, paginate={"per_page": 30, "page": 1}).configure(table)

    return render(request, 'employee_directory/update_form.html', {'form': form})
コード例 #5
0
def update():
    form = UpdateForm()

    if form.validate_on_submit():
        conn = sqlite3.connect('NBA.db')
        c = conn.cursor()

        #Update the player into the 'Player' table
        #query = 'update into Player VALUES (' + "'" + form.team_name.data + "',"  + "'" + form.player_ID.data + "'," + "'" + form.player_name.data + "'," + "'" + form.player_age.data + "'," + "'" + form.nationality.data + "'," + "'" + form.salary.data + "'," + "'" + form.position.data + "'" + ')' #Build the query

        if form.team_name is not None:
            query = 'update PLAYER set Team_Name = "' + form.team_name.data + '", Player_Age = "' + form.player_age.data + '" ,Position = "' + form.position.data + '"where Player_ID = ' + form.player_ID.data + ''
            c.execute(query)  #Execute the query
            conn.commit()  #Commit the changes
        #if form.player_age is not None:
        #   query = 'update PLAYER set Player_Age = "' + form.player_age.data + '" where Player_ID = ' + form.player_ID.data + ''
        #    c.execute(query) #Execute the query
        #    conn.commit() #Commit the changes
        #if form.position is not None:
        #    query = 'update PLAYER set Position = "' + form.position.data + '" where Player_ID = ' + form.player_ID.data + ''
        #    c.execute(query) #Execute the query
        #    conn.commit() #Commit the changes

        flash(f'Update succeed for Player {form.player_ID.data}!', 'success')
        return redirect(url_for('team'))
    return render_template('update.html', title='update', form=form)  #修改LOGIN
コード例 #6
0
    def post(self):
        arg = self.request.arguments
        result = UserSystem.queryById(self.current_user.decode()).fetchone()

        diff = arg['username'][0].decode() != result[1]
        diff += arg['email'][0].decode() != result[3]
        diff += arg['phone'][0].decode() != result[4]

        if diff == 0:
            self.write(json.dumps({'errors': 'Nothing'}))
        else:
            arg['originUsername'] = [result[1]]
            arg['originEmail'] = [result[3]]
            arg['originPhone'] = [result[4]]

            form = UpdateForm(arg)

            errors = "Failed"
            if form.validate():
                yield UserSystem.update(result[0], arg['username'][0].decode(),
                                        arg['email'][0].decode(),
                                        arg['phone'][0].decode())
                errors = "Success"
            self.set_header("Content-Type", "application/json")

            retval = form.errors
            retval['errors'] = errors
            yield self.write(json.dumps(retval))
コード例 #7
0
def update():  
    form =UpdateForm()
    if request.method == 'POST':
        if form.validate() == False:
            return render_template('update.html', form = form)
        else:
            value1=request.form['fname']
            value2=request.form['lname']
            value3=request.form['age']
            value4=request.form['mobileno']
            value5=request.form['email']
            value6=request.form['password']
            with open("json_file.json","r") as f:
                    data = f.read() 
                    d = json.loads(data)
                    value=str(value5)
                    i = [i for i in d if i['Email'] == value]
                    i[0]['Firstname']=value1
                    i[0]['Lastname']=value2
                    i[0]['Mobileno']=value4
                    i[0]['Age']=value3  
                    i[0]['Email']=value5
                    i[0]['Password']=value6                                  
                    info=json.dumps(d,indent=4,sort_keys=True)
                    with open("json_file.json",'w') as file1:
                        file1.write(info)  
                    return "successfully updated" 
    elif request.method == 'GET':
            return render_template('update.html', form = form)
コード例 #8
0
ファイル: views.py プロジェクト: kblauer/kinder-updates
def create(request):
    username = None
    group = 'parent'
    
    if request.user.is_authenticated():
        username = request.user.username
        if request.user.has_perm('updates.add_update'):
            group = 'teacher'
            
    if request.POST:
        form = UpdateForm(request.POST)
        if form.is_valid():
            form.save()
            
            return HttpResponseRedirect('/updates/all')
        
    else:
        form = UpdateForm()
        
        args = {}
        args.update(csrf(request))
        
        args['form'] = form
        args['username'] = username
        args['group'] = group
        
        return render_to_response('create_update.html', args)
コード例 #9
0
ファイル: main.py プロジェクト: preetpalsinghmehra/Academy
def updateinfo():
    form = UpdateForm()
    if form.validate_on_submit():
        if form.picture.data:
            picture_file = save_picture(form.picture.data)
            current_user.image_file = picture_file
        current_user.name = form.name.data
        current_user.email = form.email.data
        current_user.mobile = form.mobile.data
        current_user.address = form.address.data
        current_user.city = form.city.data
        current_user.state = form.state.data
        current_user.zip = form.zip.data
        db.session.commit()
        flash('Your Profile has been Updated!!', 'success')
        return redirect(url_for('account'))
    elif request.method == 'GET':
        form.name.data = current_user.name
        form.email.data = current_user.email
        form.mobile.data = current_user.mobile
        form.address.data = current_user.address
        form.city.data = current_user.city
        form.state.data = current_user.state
        form.zip.data = current_user.zip
    return render_template('updateinfo.html', form=form)
コード例 #10
0
def changePref():
    form = UpdateForm()
    if request.method == 'POST':
        if form.validate() == False:
            return render_template("changePref.html", form=form)
        else:
            risk_level = form.riskLevel.data
            if (risk_level == 'Volatile'):
                risk_level_int = 0
            elif (risk_level == 'Moderate'):
                risk_level_int = 1
            elif (risk_level == 'Safe'):
                risk_level_int = 2
            userName = session['username']
            change_user = User.query.filter_by(username=userName).first()
            change_user.inv_amount = form.investment.data
            change_user.risk_level = risk_level_int
            db.session.commit()
            change_user = User.query.filter_by(username=userName).first()
            session['username'] = change_user.username
            session['email'] = change_user.email
            session['investment'] = change_user.inv_amount
            session['risk_level'] = change_user.risk_level
            zp = Zipliner.getInstance()
            zp.resetPlots()
            return redirect(url_for('portfolio'))
    else:
        return render_template("changePref.html", form=form)
コード例 #11
0
def profile():
    form = UpdateForm()
    image_file = url_for('static',
                         filename='images/' + current_user.image_file)

    if form.validate_on_submit():
        if form.password.data == form.retypePassword.data:
            hashed_password = generate_password_hash(form.password.data,
                                                     method='sha256')
            user = User.query.filter_by(id=current_user.id).first()
            if request.method == 'POST' and form.image.data:
                picture_file = save_picture(form.image.data)
                user.image_file = picture_file
            user.password = hashed_password
            user.username = form.username.data
            user.email = form.email.data
            db.session.commit()
            flash('successful update')
            return redirect(url_for('dashboard'))
        else:
            flash('incorrect password')

    form.username.data = current_user.username
    form.email.data = current_user.email

    return render_template('profile.html',
                           name=current_user.username,
                           form=form,
                           image_file=image_file)
コード例 #12
0
ファイル: views.py プロジェクト: jasonshere/MAPS
def account():
    """
    show account page
    :return: render page
    """
    form = UpdateForm(request.form)
    if request.method == 'GET':
        form.username.data = session['User']['username']
        form.name.data = session['User']['name']
        form.email.data = session['User']['email']
        form.age.data = session['User']['age']
        form.sex.data = session['User']['sex']
        form.birthday.data = session['User']['birthday']
        form.phone.data = session['User']['phone']
    if request.method == 'POST' and form.validate():
        # update data of patient
        ps = PatientService()
        payload = {'patient': form.data}
        res, data = ps.update(payload)
        if res:
            return render_template('patient/account.html',
                                   **patientSetting(),
                                   form=form)
    return render_template('patient/account.html',
                           **patientSetting(),
                           form=form)
コード例 #13
0
ファイル: views.py プロジェクト: jmjuanico/likereader
def update():
    error = None
    form = UpdateForm()
    next = get_redirect_target()
    next = retain_before_auth_page(next)
    if request.method == 'POST':
        if request.form['submit'] == 'cancel':
            return redirect_back('index')
        else:
            if form.validate_on_submit():
                user = User.query.filter_by(username=form.username.data).first()
                if user:
                    # creates and sends the token which contains the secret keys
                    token = generate_confirmation_token(user.email)
                    confirm_update_url = url_for('confirm_password', token=token, _external=True)
                    update_notification(user, confirm_update_url)

                    flash('A confirmation email has been sent.', 'success')
                    return redirect_back('index')
                else:
                    flash('Invalid username.', 'danger')
                    return render_template('update.html', form=form, error=error, next=next)
            else:
                flash('Invalid username.', 'danger')
                return render_template('update.html', form=form, error=error, next=next)
    else:
        return render_template('update.html', form=form, error=error, next=next)
コード例 #14
0
def user_profile_update(user_id):
    form = UpdateForm()
    cursor = g.db.execute('SELECT * FROM user WHERE id=? ', [user_id])
    res = cursor.fetchone()
    if res is None:
        return jsonify({'code': 404})  # 没有改用户 404
    if session['user_id'] == res[0]:
        if request.method == 'POST' and form.validate_on_submit():  # 提交了form
            name, password = request.form['username'], request.form['password']
            real_name, tel = request.form["real_name"], request.form['tel']
            if md5_user_psw(res[1], password) == res[2]:  # 提交了form且密码正确
                g.db.execute(
                    'UPDATE user SET username=?,pass_hash=?,real_name=?,tel=? WHERE id=?',
                    [
                        name,
                        md5_user_psw(name, password), real_name, tel, user_id
                    ])
                return redirect(
                    url_for('user_profile', user_id=session['user_id']))
            else:
                flash(message='password error')
                return render_template('update.html',
                                       title='Update',
                                       form=form)
        else:  # 没有提交form
            form.username.data = res[1]
            form.real_name.data = res[3]
            form.tel.data = res[4]
            return render_template('update.html', title='Update', form=form)
    # 不是本用户访问
    return redirect(url_for('hello'))
コード例 #15
0
def update_pattern(pattern_id):
    """
   Updates a pattern on Mongo DB 
    """
    try:
        form = UpdateForm(mongo.db, data=request.form.to_dict())
        is_valid: bool = form.validate()

        if is_valid:
            patterns = mongo.db.patterns
            patterns.update({'_id': ObjectId(pattern_id)},
                            {
                'category_name': request.form.get('category_name'),
                'pattern_name': request.form.get('pattern_name'),
                'pattern_by': request.form.get('pattern_by'),
                'pattern_yarn_weight': request.form.get('pattern_yarn_weight'),
                'pattern_gauge': request.form.get('pattern_gauge'),
                'pattern_needle_size': request.form.get('pattern_needle_size'),
                'pattern_yardage': request.form.get('pattern_yardage'),
                'pattern_size': request.form.get('pattern_size'),
                'pattern_language': request.form.get('pattern_language'),
                'pattern_url': request.form.get('pattern_url'),
                'pattern_notes': request.form.get('pattern_notes'),
                'pattern_img': request.form.get('pattern_img'),
                'pattern_difficulty': request.form.get('pattern_difficulty')
            })
            return pattern(pattern_id)
        return redirect(url_for('add_pattern', showError=True))
    except Exception:
        return render_template('404.html')
コード例 #16
0
def update(_id):
    todo = TodoModel.find_by_id(_id)
    form = UpdateForm(obj=todo)
    if form.validate_on_submit():
        todo.title = form.title.data
        todo.remarks = form.remarks.data
        todo.save_to_db()
        return redirect(url_for('view.home'))
    return render_template('update.html', form=form, todo=todo)
コード例 #17
0
def update():
    form = UpdateForm(request.form)
    if request.method == 'POST' and form.validate():
        user = models.Users(id_no=form.new_id.data,
                            name=form.new_name.data,
                            course=form.new_course.data)
        user.update()
        return redirect('/')
    else:
        return render_template('update.html', form=form)
コード例 #18
0
def podcast_update(podcast_id):
    """
  Function that checks whether user is logged in. For logged in user it opens 
  page with a form that allows user to edit existing content to the database.
  It searches collection podcasts in the detabase and displays pre-filled in form
  with the content of a podcast found using value "ObjectId(podcast_id)" of a key "_id".
  Used request.method == 'GET' following advice from 
  https://romain.dorgueil.net/wiki/python/wtforms and https://stackoverflow.com/a/23714791
  to populate update form with existing in database details for the podcast that user 
  wants to amend.  
  For users that are not logged in it redirects to login page.
  """
    if 'username' not in session:
        flash(f'Oops... you need to be logged in to see this page.', 'danger')
        return redirect(url_for('login'))
    else:
        update_form = UpdateForm()
        picked_podcast = mongo.db.podcasts.find_one(
            {'_id': ObjectId(podcast_id)})

    if request.method == 'GET':
        update_form.podcast_title.data = picked_podcast['podcast_title']
        update_form.podcast_imgurl.data = picked_podcast['podcast_imgurl']
        update_form.origin.data = picked_podcast['origin']
        update_form.release_year.data = picked_podcast['release_year']
        update_form.description.data = picked_podcast['description']
        update_form.is_favourite.data = picked_podcast['is_favourite']
        update_form.no_episodes.data = picked_podcast['no_episodes']
        update_form.podcast_link.data = picked_podcast['podcast_link']

    elif update_form.validate_on_submit():
        mongo.db.podcasts.update_one({'_id': ObjectId(podcast_id)}, {
            '$set': {
                'podcast_title': update_form.podcast_title.data,
                'podcast_imgurl': update_form.podcast_imgurl.data,
                'origin': update_form.origin.data,
                'release_year': update_form.release_year.data,
                'description': update_form.description.data,
                'is_favourite': update_form.is_favourite.data,
                'no_episodes': update_form.no_episodes.data,
                'podcast_link': update_form.podcast_link.data
            }
        })
        flash(f'Podcast details updated sucessfully.', 'success')
        return redirect(url_for('my_account'))

    else:
        flash(f'Error updating podcast. Please try again', 'danger')
        return redirect(url_for('my_account'))

    return render_template('pages/podcast-update.html',
                           form=update_form,
                           podcast=picked_podcast,
                           title='Update podcast details',
                           head='Edit Podcast')
コード例 #19
0
ファイル: server.py プロジェクト: akul08/gossip_girl
def updatedb():
    # form to send notifications and update db
    form = UpdateForm()
    form.room.choices = zip(all_rooms, all_rooms)
    if form.validate_on_submit():
        mongo.db.rooms.insert({'room': form.room.data,
                               'update': form.update.data,
                               'ts': datetime.datetime.now()})
        flash('Message sent!')
        return redirect(url_for('updatedb'))
    return render_template('updatedb.html', form=form)
コード例 #20
0
ファイル: task4.py プロジェクト: Caetan/web_scraper
def update_aircraft(aircraft_id):
    form = UpdateForm()
    if request.method == 'POST' and form.validate():
        # Add new aircraft to DB
        operator = form.operator.data
        model = form.model.data
        registration = form.registration.data
        cn_fl = form.cn_fl.data
        update_obj(aircraft_id, operator, model, registration, cn_fl)
        aircrafts = retrive_obj(2, 0, "")
        return redirect('/aircrafts')
    return render_template('aircraft_update_form.html', form=form)
コード例 #21
0
def get_name(request):
    form=NameForm()
    form1=UpdateForm()
    s8 = prediction_content.get_prediction_content()
    json_pre = json.dumps(s8)

    # if this is a POST request we need to process the form data
    if request.method == 'POST' and 'search' in request.POST:
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            #start of search processing time
            start_time=time.time()
            your_name = request.POST.get('your_name')
            your_name1=your_name
            s=search1.get_search_result(your_name1)
            s1=search1.get_file_name()
            s3=[]
            s4=search1.pre()
            s5=search1.get_knownerror()
            for i in s1:
                if i not in s3:
                    s3.append(i)
            s2=zip(s,s1,s4,s5)
            c=len(s)
            tim=time.time()-start_time
            tim=str(tim)+" sec"
            #end of search process time
            form=NameForm()

            return render(request,'myapp/thanks.html',{'name':your_name1,'file':s3,'filename':s2,'number':c,'result':s,'form':form,'form1':form1,'soln':s,'ti':tim,'json_pre':json_pre})

    if request.method == 'POST' and 'update' in request.POST:
        form1 = UpdateForm(request.POST)
        if form1.is_valid():
            question = request.POST.get('question')
            answer = request.POST.get('comment')
            pre = request.POST.get('pre')
            file_choice=request.POST.get('file_choice')
            print answer

            print question
            print file_choice
            form1 = UpdateForm()
            update.update(question,answer,pre,file_choice)

            return render(request, 'myapp/thanks.html',
                          {'form':form,'form1':form1,'json_pre':json_pre})
    else:
            form = NameForm()
            form1=UpdateForm()


    #template = loader.get_template("myapp/name.html")
    context = {'form': form,'form1':form1,'json_pre':json_pre}
    #return HttpResponse(template.render(context, request))
    return render(request, "myapp/name.html", context)
コード例 #22
0
ファイル: views.py プロジェクト: vitaliyharchenko/sportcourts
def update(request):
    user = User.objects.get(email=request.user.email)
    form = UpdateForm(request.POST or None, request.FILES or None, instance=user)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            messages.success(request, "Успешно сохранено!", extra_tags='info')
            return redirect('user_update')
        else:
            messages.warning(request, "Некорректные данные", extra_tags='info')
    context = {'avatar_url': user.avatar, 'form': form, 'passform': ChangePasswordForm}
    return render(request, 'user_update.html', context)
コード例 #23
0
def update_profile(request):
    form = UpdateForm(request.POST or None, instance=request.user)
    if form.is_valid():
        form.save()
        messages.success(request, 'Success, your project was saved!')

    context = {
        "form": form,
        "page_name": "Update",
        "button_value": "Update",
        "links": ["logout"],
    }
    return render(request, 'auth_form.html', context)
コード例 #24
0
ファイル: routes.py プロジェクト: wronaq/cryptoQuickView
def submitUpdate():
    form = UpdateForm()

    if form.validate_on_submit():

        updateDataBase(currency='{}'.format(form.currencyUpdate.data),
                       dataUpdate='{}'.format(form.dateUpdate.data),
                       highRate=form.highUpdate.data,
                       lowRate=form.lowUpdate.data)

        return redirect(url_for('tables'))

    return render_template('updateDB.html', form=form)
コード例 #25
0
ファイル: flaskblog.py プロジェクト: yawar1/flask-app
def account():
    if not(session.get('user')):
        return redirect(url_for('login'))
    form=UpdateForm()
    mycur.execute(f""" SELECT email FROM reg WHERE user= %s """,(session.get('user'),))
    email=mycur.fetchone()[0]
    if form.validate_on_submit():
        result_user=False
        if form.username.data != session.get('user'):
            mycur.execute(f'SELECT * FROM reg WHERE user= %s ',(form.username.data,))
            result_user=mycur.fetchone()
        result_email=False    
        if form.email.data != email:
            mycur.execute(f'SELECT * FROM reg WHERE email=%s ',(form.email.data,))
            result_email=mycur.fetchone()
        if not(result_user):
            if not(result_email):
                
                
                mycur.execute(""" UPDATE reg SET email = %s WHERE user = %s """,(form.email.data,session.get('user')))
                db.commit()
               
                mycur.execute(""" SET FOREIGN_KEY_CHECKS =0 """ )
                mycur.execute(""" UPDATE reg SET user = %s WHERE user = %s """,(form.username.data,session.get('user')))
                mycur.execute(""" UPDATE posts SET author = %s WHERE author = %s """,(form.username.data,session.get('user')))
                mycur.execute(""" SET FOREIGN_KEY_CHECKS =1 """ )
                db.commit()
                session['user']=form.username.data
                if form.dp.data:
                    mycur.execute(f""" SELECT image_file FROM reg WHERE user= %s """,(session.get('user'),))
                    image_file=mycur.fetchone()[0]
                    file_path=os.path.join(app.root_path,'static\profile_pics',image_file)
                    if (image_file != 'default.jpg'):
                        os.remove(file_path)
                    
                
                    picture=save(form.dp.data)
                    mycur.execute(""" UPDATE reg SET image_file = %s where user = %s """,(picture,session.get('user')))
                    db.commit()
                flash('changed Successfully','success')
            else:
                flash("Account with that email already exists!",'danger')
        else:
            flash("Username taken,try a diffrent one",'danger')        
    mycur.execute(f""" SELECT email,image_file FROM reg WHERE user= %s """,(session.get('user'),))
    email,image_file=mycur.fetchone()
    form.email.data=email
    form.username.data=session.get('user')
    profile_pic=url_for('static',filename='profile_pics/'+image_file)
    return render_template('account.htm',email=email,form=form,current_address='/account',dp=profile_pic)
コード例 #26
0
def insert_pattern():
    """
    Add a pattern to Mongo DB and displays it in the patterns section if sucessful
    """

    form = UpdateForm(mongo.db, data=request.form.to_dict())
    is_valid: bool = form.validate()

    if is_valid:
        patterns = mongo.db.patterns
        patterns.insert_one(request.form.to_dict())
        return redirect(url_for('get_patterns'))
    else:
        return redirect(url_for('add_pattern', showError=True))
コード例 #27
0
ファイル: views.py プロジェクト: haikezegwaard/buzzart
def compose_update(request, project_id):
    project = Project.objects.get(id=project_id)
    if request.method == 'POST':
        form =  UpdateForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/dashboard/{}'.format(project_id))
    else:
        data = { 'project': project,
                 'posted': datetime.datetime.now()
               }
        form = UpdateForm(initial= data)
    return render(request, 'updates/compose-update.html',
                  {'form': form,
                   'project': project})
コード例 #28
0
def update_member(member_id):
    form = UpdateForm(request.form)
    member = Member.query.get(member_id)
    if request.method == 'POST' and form.validate():
        id = form.id.data
        name = form.name.data
        age = form.age.data
        comment = form.comment.data
        with db.session.begin(subtransactions=True):
            member = Member.query.get(id)
            member.name = name
            member.age = age
            member.comment = comment
        db.session.commit()
        return redirect(url_for('member_list'))
    return render_template('update_member.html', form=form, member=member)
コード例 #29
0
ファイル: views.py プロジェクト: masapon06/flask_fushinsha
def update_witness(person_id):
    form = UpdateForm(request.form)
    person = Person.query.get(person_id)
    if request.method == 'POST' and form.validate():
        id = form.id.data
        name = form.name.data
        age = form.age.data
        comment = form.comment.data
        with db.session.begin(subtransactions=True):
            person = Person.query.get(id)
            person.name = name
            person.age = age
            person.comment = comment
        db.session.commit()
        return redirect(url_for('witness_list'))
    return render_template('update_witness.html', form=form, person=person)
コード例 #30
0
def account():
    form = UpdateForm()
    if request.method =='POST':
        if request.form['delete']=='1':
            delete_user(current_user.id)
            logout_user()
            return redirect(url_for('login_page'))
        else:
            if form.validate_on_submit():
                update_user(form.username.data,form.mail.data,current_user.id)
                flash(f'Updated Account: {form.username.data}, {form.mail.data}!', 'success')
                return redirect(url_for('account'))
            else:
                flash(f'Failed to Update Account to {form.username.data}, {form.mail.data}!', 'danger')

    return render_template("account.html", current_user= current_user, form = form)
コード例 #31
0
def index():
	update_form = UpdateForm()
	liquidate_form = LiquidateForm()
	add_form = AddForm()
	find_port_form = FindPortForm()


	if find_port_form.SubmitFind_Port.data:
		try:
			dataframe = getPortfolioValue(find_port_form.Find_Portfolio.data, "database.xlsx")
			producePNG(dataframe, "uploads/image.png")
			portfolioComponents = getPortfolioComponents(find_port_form.Find_Portfolio.data, "database.xlsx")
			portfolioComponents = portfolioComponents.to_string()
			portfolioStats = getStats(dataframe)
			return redirect(url_for('display', portfolioStats=portfolioStats, portfolioComponents=portfolioComponents))
		except:
			print("ERROR EMAIL NOT IN DATABASE")

	if add_form.SubmitAdd.data:
		addtoDB(add_form.Add_Portfolio.data, add_form.Add_Ticker.data, float(add_form.Price.data), int(add_form.Quantity.data), "database.xlsx")

	if liquidate_form.SubmitLiquidate.data:
		removeDB(liquidate_form.Liquidate_Portfolio.data, liquidate_form.Liquidate_Ticker.data, "database.xlsx", "database.xlsx")
	
	if update_form.SubmitUpdate.data:
		changeQuantity(update_form.Update_Portfolio.data, update_form.Update_Ticker.data, int(update_form.New_Quantity.data), "database.xlsx", "database.xlsx")
	
	return render_template('index.html', add_form=add_form, liquidate_form=liquidate_form, update_form=update_form, find_port_form=find_port_form)
コード例 #32
0
    def put(self):
        """
        Update current user's profile.
        """
        user = g.user
        data = api.payload
        form = UpdateForm.from_json(data)
        if form.validate():
            password = data.get('password')
            full_name = data.get('full_name', user.full_name)
            address = data.get('address', user.address)
            email = data.get('email', user.email)
            phone_number = data.get('phone_number', user.phone_number)
            description = data.get('description', user.description)
            tags = data.get('tags', user.tags)

            if data.get('tags') is not None: user.add_tags(tags)

            if full_name: user.full_name = full_name.lower()
            if address: user.address = address.lower()
            user.email = email.lower()
            user.phone_number = phone_number
            user.description = description
            if password: user.hash_password(password)
            db.session.add(user)
            db.session.commit()
            return {'element': user.to_json()}, 201
        return {"message": form.errors}, 400
コード例 #33
0
def viewUpdates():
    from tables import Update, User
    form = UpdateForm()
    if request.method == 'POST' and form.validate_on_submit():
        updateContent = form.content.data
        newUpdate = Update(content=updateContent,
                           contributorID=current_user.id)
        db.session.add(newUpdate)
        db.session.commit()
        form.content.data = ''
        return redirect(url_for('proj.viewUpdates'))
    updates = Update.query.order_by(Update.dateCreated)
    users = User.query.order_by(User.dateCreated)
    return render_template('project/updates.html',
                           updates=updates,
                           updateForm=form,
                           users=users)
コード例 #34
0
def club_info(clubname):
    club = Club.query.filter_by(name=clubname).first()

    form = UpdateForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            club.description = form.description.data
            club.tags = form.tags.data
            db.session.commit()
            flash('Club Updated!', 'success')
            return redirect(url_for('clubs'))
        else:
            flash('Login to update a club.', 'danger')
    return render_template('club.html',
                           title="Club Info",
                           form=form,
                           club=club)
コード例 #35
0
ファイル: views.py プロジェクト: gareth-lloyd/safetrip
def update(request):
    if request.method == "POST":
        safe_form = SafeForm(data=request.POST)
        help_form = HelpForm(data=request.POST)
        update_form = UpdateForm(data=request.POST)
        if help_form.is_valid():
            data = help_form.cleaned_data
            traveller = data['traveller']
            update = TravellerUpdate(traveller=traveller,
                status=STATUS_IN_DANGER,
                current_country=data['country'],
                update=data['help_message'])
            do_help_actions(traveller)
            kwargs = {'traveller_id': str(traveller.id)}
            url_name = 'help'
            if data['country']:
                url_name = 'help-country'
                kwargs['country'] = data['country']
            return HttpResponseRedirect(reverse(url_name,
                    kwargs=kwargs))
        if safe_form.is_valid():
            traveller = safe_form.cleaned_data['traveller']
            update = TravellerUpdate(traveller=traveller,
                        status=STATUS_SAFE)
            update.save()
            do_safe_actions(traveller)
            return HttpResponseRedirect(reverse('safe'))
        if update_form.is_valid():
            data = update_form.cleaned_data
            traveller = data['traveller']
            update = TravellerUpdate(traveller=traveller,
                        status=STATUS_IN_TRANSIT, update=data['message'],
                        current_country=data['country'])
            do_update_actions(traveller)
            return HttpResponseRedirect(reverse('updated'))
    else:
        safe_form = SafeForm()
        help_form = HelpForm()
        update_form = UpdateForm()
    return render_to_response('update.html',
            {'safe_form': safe_form,
            'help_form': help_form,
            'update_form': update_form},
            context_instance=RequestContext(request))
コード例 #36
0
def profile():
    """Update profile for current user."""

    form = UpdateForm(obj=g.user)
    if form.validate_on_submit():
        if (User.authenticate(g.user.username, form.password.data)):
            if (form.email.data):
                g.user.email = form.email.data
            if (form.first_name.data):
                g.user.first_name = form.first_name.data
            if (form.last_name.data):
                g.user.last_name = form.last_name.data
            db.session.add(g.user)
            db.session.commit()
            return redirect(
                url_for('view_user_detail', username=g.user.username))
        else:
            flash("Wrong password", "danger")
            return redirect(url_for('homepage'))
    return render_template('user/edit.html', form=form)
コード例 #37
0
ファイル: views.py プロジェクト: alvz/ERP_Saarang
def handle_updates (request, owner_name = None):
    """
    Used by coords to send updates to Core.
    Cores will just see the updates they have received.

    Return a dict containing update variables.
    """
    page_owner = get_page_owner (request, owner_name)

    update_dict = dict ()
    if page_owner.groups.filter (name = 'Coords'):
        # For Coords
        update_form = UpdateForm ()
        update_status = "Blank"
        update_dict['updates'] = Update.objects.filter (author = page_owner)
        update_dict['update_form'] = update_form
        update_dict['update_status'] = update_status
    else:
        # For Core, just display all updates for his dept
        update_dict['updates'] = get_all_updates (
            page_owner.get_profile ().get_dept ())

    if request.method == 'POST':
        update_form = UpdateForm (request.POST)            
        if update_form.is_valid():
            new_update = update_form.save (commit = False)
            new_update.author = page_owner
            new_update.save ()
            update_form = UpdateForm ()
            update_status = "Success"
            update_dict['update_status'] = update_status
            return update_dict
        else:
            update_status = "Failed"
            update_dict['update_status'] = update_status
            update_dict['update_form'] = update_form
            return update_dict
    return update_dict