예제 #1
0
def delete(
        id):  #delete item matching the url-id for uniqueness of the operation
    #query the database and retrieve the member id for deleting
    qry = db.session.query(Member).filter(Member.id == id)
    member = qry.first()
    if member:
        image = member.image_file  #Get the image_file from the database and check whether the image has been uploaded or not
        if image == "noavatar92":  #Incase the user image is not yet uploaded
            image_file = url_for(
                'static', filename='img/' + member.image_file + '.png'
            )  #Manually add the extension to the image file from the database
        else:
            image_file = url_for('static', filename='img/' + member.image_file)
        form = EditForm(
            formdata=request.form, obj=member
        )  #Use the edit form since it doesnt include the phto filefield input
        if request.method == 'POST' and form.validate():
            db.session.delete(member)
            db.session.commit()

            flash("Successfully deleted member from database")
            return redirect('/')
        return render_template('examples/delete.html',
                               form=form,
                               image_file=image_file,
                               member=member)
    else:
        return 'Error deleting #{id}'.format(id=id)
예제 #2
0
def admin_profile(login):
    user = User.query.filter_by(login=login).first()
    if user == None:
        flash('User ' + login + ' not found.', 'error')
        return redirect(url_for('admin_index'))
    
    form = EditForm()
    if request.method == 'POST':
        form.login.data = user.login;
        if form.validate():
            if form.password.data == '':
                user.first_name = form.first_name.data
                user.last_name = form.last_name.data
                user.email = form.email.data
            else:
                form.populate_obj(user)
                user.passhash = encrypt_password(form.password.data)
                form.dispose_password()
                
            db.session.add(user)
            db.session.commit()
            flash(msgs['EDIT_SUCCESS'])
            return redirect(url_for('admin_profile', login=login))
        
    for field in form.errors:
        flash('<strong>' + field.capitalize() + '</strong>' + ': ' + form.errors[field][0], 'error')
        
    return render_template('admin/profile.html', form=form, user=user)
예제 #3
0
def edit(id):
    #check whether the item id exists in the database
    qry = db.session.query(Member).filter(Member.id == id)
    member = qry.first()

    if member:  # if the record exists
        image = member.image_file  #Get the image_file from the database and check whether the image has been uploaded or not
        if image == "noavatar92":  #Incase the user image is not yet uploaded
            image_file = url_for(
                'static', filename='img/' + member.image_file + '.png'
            )  #Manually add the extension to the image file from the database incase the user image hadnt been added already
        else:
            image_file = url_for(
                'static', filename='img/' + member.image_file
            )  #set the image file to the current filename stored in the database
        print(image_file)
        #pass the member objects stored in the database to the form for display and editing
        form = EditForm(formdata=request.form, obj=member)
        if request.method == 'POST' and form.validate():
            picture_fn = member.image_file  #Pass the image file of the current image for the current ovject since its not edited here
            edit_member(
                member, form
            )  #pass the newly edited form to the member model to be saved in the database
            flash('successfully updated the record')
            return redirect(url_for('search_family'))

        return render_template('examples/edit.html',
                               form=form,
                               image_file=image_file,
                               member=member)

    else:
        return 'Error loading {id}'.format(
            id=id)  #pass the <int:id> to convert the id to int
def edit():
    print("edit feature")
    # check if a user is saved in session
    if session.get('user'):

        user = db.session.query(User).filter(
            User.id == session['user_id']).first()
        print("user name:" + user.first_name + "." + user.last_name)

        if user:
            form = EditForm(formdata=request.form, obj=user)
            if request.method == 'POST' and form.validate():
                # save edits
                save_changes(user, form)
                # flask('Profile updated successfully')
                # save the user's name to the session
                session['user'] = user.first_name
                # access id value from user model of this newly added user
                session['user_id'] = user.id
                # show user dashboard view
                return redirect(url_for('index'))
            else:
                return render_template('edit_profile.html',
                                       form=form,
                                       user=session['user'])

    else:
        # user is not in session redirect to login
        return redirect(url_for('login'))
예제 #5
0
파일: view.py 프로젝트: Jules-7/library
def edit_name(url):
    prev_name = url
    e_form = EditForm(request.form)
    lib = methods.get_all_authors_and_books()
    sorted_lib = sorted(lib)
    new_lib = []
    for key in sorted_lib:
        new_lib.append([key, lib[key]])
    if request.method == 'POST' and e_form.validate():
        new_name = (e_form.new_name.data).strip()
        flag = methods.edit(prev_name, new_name)
        if flag == False:
            edit = True
            flash('Such name already exist')
            return render_template('library.html',
                                   e_form=e_form,
                                   new_lib=new_lib,
                                   edit=edit)
        return redirect(url_for('show_library'))
    else:
        flash('Insert name')
        edit = True
        return render_template('library.html',
                               e_form=e_form,
                               new_lib=new_lib,
                               edit=edit)
예제 #6
0
파일: main.py 프로젝트: zcb7/DatabaseGame
def new_user():

    form = EditForm(request.form)

    if request.method == 'POST' and form.validate():
        userdata = Userdata()
        save_changes(userdata, form, new=True)
        flash('User created successfully!')
        return redirect('/')

    return render_template('new_user.html', form=form)
예제 #7
0
def edit():
    form = EditForm()
    if request.method == 'POST' and form.validate():
        g.user.username = form.username.data
        g.user.about_me = form.about_me.data
        g.user.password = form.password.data
        db.session.add(g.user)
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('edit'))
    else:
        form.username.data = g.user.username
        form.about_me.data = g.user.about_me
    return render_template('edit.html', form=form)
예제 #8
0
def editprofile():
    user = Profiles.query.filter_by(userid=current_user.get_id()).first()
    eform = EditForm()        
    if request.method == "POST" and eform.validate():  
      user.username = eform.username.data
      user.first_name = (eform.first_name.data).title()
      user.last_name = (eform.last_name.data).title()
      user.age = eform.age.data
      user.gender = eform.gender.data      
      user.initial = False
      db.session.commit()
      flash('Profile updated')
      return redirect(url_for('update'))  
    return render_template('update.html', eform=eform, pform=changePWForm(), picform=photoForm())
예제 #9
0
파일: main.py 프로젝트: zcb7/DatabaseGame
def edit(id):

    qry = db_session.query(Userdata).filter(Userdata.user_id == id)
    userdata = qry.first()

    if userdata:
        form = EditForm(formdata=request.form, obj=userdata)
        if request.method == 'POST' and form.validate():
            # save edits
            save_changes(userdata, form)
            flash('User updated successfully!')
            return redirect('/')
        return render_template('edit_user.html', form=form)
    else:
        return 'Error loading #{id}'.format(id=id)
예제 #10
0
파일: main.py 프로젝트: VSirvio/MonkeyBook
def edit_monkey():
    form = EditForm(request.form)
    rf_form = RemFriendForm()
    args = IdForm(request.args, csrf_enabled=False)

    if request.method == 'POST':
        id = form.id.data
    elif args.validate():
        id = args.id.data
    else:
        abort(404)

    monkey = Monkey.query.filter_by(id=id).first_or_404()
    friends = monkey.friends.order_by(Monkey.name)
    friends = [dict(id=f.id, name=f.name) for f in friends]
    form.bf.choices = [(-1, '-')] + [(f['id'], f['name']) for f in friends]

    if request.method == 'POST':
        if form.validate():
            monkey.name = form.name.data
            monkey.age = form.age.data
            monkey.email = form.email.data

            if form.bf.data == -1:
                monkey.bf = None
            else:
                q = Monkey.query.filter_by(id=form.bf.data)
                monkey.bf = q.first_or_404()

            db.session.commit()
            flash(form.name.data + ' successfully edited')
            return redirect(url_for('list_monkeys'))
        else:
            monkey = dict(id=form.id.data, name=form.name.data,
                          age=form.age.data, email=form.email.data,
                          bf=form.bf.data, friends=friends)
            return render_template('edit.html', form=form,
                                   rf_form=rf_form, monkey=monkey)

    form.bf.default = -1 if monkey.bf is None else monkey.bf.id
    form.process()

    monkey = dict(id=monkey.id, name=monkey.name,
                  age=monkey.age, email=monkey.email,
                  friends=friends)

    return render_template('edit.html', form=form,
                           rf_form=rf_form, monkey=monkey)
예제 #11
0
def new():
    form = EditForm()

    if request.method == 'POST':
        if form.validate() == False:
            flash('All fields are required.')
            return render_template('new.html', form=form)
        else:
            post = Post(title = form.title.data,
                        body = form.body.data)
            db.session.add(post)
            db.session.commit()
            return redirect(url_for('index'))

    elif request.method == 'GET':
        return render_template('new.html', form=form)
예제 #12
0
파일: main.py 프로젝트: zcb7/DatabaseGame
def delete(id):

    qry = db_session.query(Userdata).filter(Userdata.user_id == id)
    userdata = qry.first()

    if userdata:
        form = EditForm(formdata=request.form, obj=userdata)
        if request.method == 'POST' and form.validate():
            db_session.delete(userdata)
            db_session.commit()

            flash('User deleted successfully!')
            return redirect('/')
        return render_template('delete_user.html', form=form)
    else:
        return 'Error deleting #{id}'.format(id=id)
예제 #13
0
파일: serv.py 프로젝트: NSkelsey/pcomment
def edit_posted_resp(response_id):
    form = EditForm(request.form)
    if request.method == 'POST' and form.validate():
       response = session.query(Response).get(response_id)
       form.populate_obj(response)
       response.cleaned_html = clean_html_email(response.raw_html)
       session.add(response)
       session.commit()
       return redirect("/r/%s" % response_id)
    else:
        response = session.query(Response).get(response_id)
        account = response.account
        response.raw_html = response.cleaned_html
        form = EditForm(obj=response)
        return render_template('edit_post.jinja2.html',
                response=response,
                account=account,
                form=form,)
예제 #14
0
파일: view.py 프로젝트: Jules-7/library
def edit_name(url):
    prev_name = url
    e_form = EditForm(request.form)
    lib = methods.get_all_authors_and_books()
    sorted_lib = sorted(lib)
    new_lib = []
    for key in sorted_lib:
        new_lib.append([key, lib[key]])
    if request.method == "POST" and e_form.validate():
        new_name = (e_form.new_name.data).strip()
        flag = methods.edit(prev_name, new_name)
        if flag == False:
            edit = True
            flash("Such name already exist")
            return render_template("library.html", e_form=e_form, new_lib=new_lib, edit=edit)
        return redirect(url_for("show_library"))
    else:
        flash("Insert name")
        edit = True
        return render_template("library.html", e_form=e_form, new_lib=new_lib, edit=edit)
예제 #15
0
파일: wikt.py 프로젝트: jleclanche/Wikt
def article_edit(article):
	form = EditForm(request.form)

	if request.method == "POST" and form.validate():
		summary = CommitMessage(form.summary.data)
		contents = form.text.data.strip()

		if article.file:
			if contents == article.file.data.decode().strip():
				# No changes.
				flash("No changes.")
				return redirect(url_for("article_view", path=article.path))

			if not contents and not summary:
				# The page has been blanked.
				summary.default_note("Blanked the page")
		else:
			# the page is new
			if not contents:
				# The page doesn't exist and has been sent blank. Ignore the commit.
				flash("The page was not created.")
				return redirect(url_for("article_view", path=article.path))
			else:
				summary.default_note('Created page with "{}"'.format(summarize(contents)))

		if form.minor_edit.data:
			summary.notes.add("Minor-Edit")

		summary.default_note("→ [[{}]]".format(article.title))
		article.save(clean_data(contents), summary.get_message())
		flash("Your changes have been saved")
		return redirect(url_for("article_view", path=article.path))

	if article.file is not None:
		form.text.data = article.file.data.decode().strip()

	return render_template("article/edit.html", article=article, form=form)
예제 #16
0
class UpdateFormProcessor(FormProcessor):
    def __init__(self, *args, **kwargs):
        super(UpdateFormProcessor, self).__init__(*args, **kwargs)
        self.select_form()

    def select_form(self):
        if self.page.form:
            self.form = self.page.form
            self.process_form()
        else:
            self.get_form()
            self.form_template = self.get_form_template()
            self.rendered_form = self.render_form()

    def get_form(self):
        self.form = EditForm()
        self.form.nickname.data = g.user.nickname
        self.form.about_me.data = g.user.about_me

    def process_form(self):
        if self.form.validate():
            g.user.nickname = self.form.nickname.data
            g.user.about_me = self.form.about_me.data
            if self.form.photo.data != '':
                g.user.photo = self.form.photo.data
            db.session.add(g.user)
            db.session.commit()
            if request.is_xhr:
                pass
            else:
                self.form = None
                self.rendered_form = None
        else:  # Return errors
            self.template = "members_form.html"
            self.form_template = self.get_form_template()
            self.rendered_form = self.render_form()
예제 #17
0
def profile():
    if 'email' not in session:
        return redirect(url_for('index'))
    groupnameList = []
    grouplist = []
    user = User.query.filter_by(email = session['email']).first()
    nickname = user.nickname
    if user is None:
        return redirect(url_for('index'))
    else:
        groupInfo = Group.query.filter_by(owner=session['email']).all()
        if groupInfo is not None:
            for ele in groupInfo:
                groupnameList.append(ele.groupname)
        if user.grouplist != "":
            grouplist = user.grouplist.split(",")

    number = [""]

    def makePicture(length):
        weight = Weight.query.filter_by(email = session['email']).first()
        if weight is not None:
            daysFromLast = (datetime.now(pytz.timezone(weight.timezone)).date() - weight.lastupdated).days
            weightarray = weight.weight.split(",")
            recordarray = []
            day = []
            labels = []
            reduce = (length / 30) + 1
            plt.figure(figsize=(12, 4))
            if length - daysFromLast > 1:
                for i in range(0, daysFromLast):
                    recordarray.append(None)
                for i in range(0, length - daysFromLast):
                    if len(weightarray) > 0:
                        recordarray.append(float(weightarray.pop()))
                    else:
                        recordarray.append(None)
                recordarray.reverse()
                
                def getfirst(array):
                    for ele in array:
                        if ele != None:
                            return ele
                def getlast(array):
                    array.reverse()
                    return getfirst(array)
                
                number[1] = getfirst(recordarray)
                number[2] = getlast(recordarray)
                recordarray.reverse()
                for i in range(0, length):
                    
                    day.append(i)
                    if reduce == 0 or i%reduce == 0:
                        labels.append(str(datetime.now(pytz.timezone(weight.timezone)).date() - timedelta(i)))
                labels.reverse()
                for i in range(0, length):
                    plt.plot(day[i],recordarray[i], linestyle="None",marker = "o", markersize = 8, color = "green")
                    #zhfont1 = matplotlib.font_manager.FontProperties(fname='/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc')
	            plt.plot(day, recordarray, linestyle="solid",color="#2BCE48",linewidth=3,label=unicode(weight.nickname) if i ==0 else "")
                plt.legend(loc='best',prop=prop)
                file = "/var/www/weight_overflow/files/static/weightgram/users/" + nickname
                plt.xticks(day, labels, rotation=45)
                plt.subplots_adjust(bottom=0.30)
                if reduce != 0:
                    plt.xticks(np.arange(min(day), max(day)+1, reduce))
                if os.path.exists(file):
                    filenumber = int(os.listdir(file)[0].split(".")[0][1:])
                    filenumber += 1
                    number[0] = str(filenumber)
                    os.remove(file + "/w" + str(filenumber - 1) + ".png")
                    plt.savefig(file + "/w" + str(filenumber) + ".png")
                else:
                    os.mkdir(file)
                    plt.savefig(file + "/w0.png")
                    number[0] = "0"
                plt.clf()
                return True
            else:
                return False
        return False

    warn = ""
    form = EditForm(prefix = "form")
    form1 = WeightForm(prefix = "form1")
    form2 = UserProgressForm(prefix = "form2")
    newuser = False
    timezoneRecorded = False
    message = ""
    weight = Weight.query.filter_by(email = session['email']).first()
    if weight != None:
        if len(weight.weight.split(",")) == 1:
            newuser = True
    else:
        newuser = True
    if user.timezone != None:
        timezoneRecorded = True


    if request.method == 'POST':
                #for weight form

        if form1.submit.data and form1.validate():

            user = Weight.query.filter_by(email = session['email']).first()
            
            if user == None:
                currentUser = User.query.filter_by(email = session['email']).first()
                grouplist = User.query.filter_by(email = session['email']).first().grouplist
                newWeight = Weight(session['email'],form1.todaysweight.data,datetime.now(pytz.timezone(currentUser.timezone)).date(),datetime.now(pytz.timezone(currentUser.timezone)).date(),grouplist, nickname, currentUser.timezone, currentUser.target)
                db.session.add(newWeight)
                db.session.commit()
            
            if user != None:
                if (datetime.now(pytz.timezone(user.timezone)).date() - user.lastupdated).days == -1:
                    
                    weight = Weight.query.filter_by(email = session['email']).first()
                    if user.begindate == user.lastupdated:
                        weight.begindate = datetime.now(pytz.timezone(user.timezone)).date()
                        weight.weight = form1.todaysweight.data
                    else:
                        temp = weight.weight.split(",")
                        temp[-2] = form1.todaysweight.data
                        temp.pop()
                        weight.weight = ','.join(temp)
                        weight.daysAbsent = weight.daysAbsent - 1
                    
                    weight.lastupdated = datetime.now(pytz.timezone(user.timezone)).date()
                    db.session.commit()
                else:
                
                
                
                
                
                
                    #first day recording, if it's not the first day, go to else
                    temp = (datetime.now(pytz.timezone(user.timezone)).date() - user.lastupdated).days
                    if temp > 0:
                        user.daysAbsent = temp
                    if user.daysAbsent == 0:
                        user.weight = "%.2f"%(float(form1.todaysweight.data))
                    #after first day
                    else:
                        #days that this ppl is not recording the weight info, this will remain the same if
                        #ppl try to modify today's weight.
                        #check if user have already entered today's weight
                        exist = False
                        if user.lastupdated == datetime.now(pytz.timezone(user.timezone)).date():
                            exist = True
                        else:
                            user.lastupdated = datetime.now(pytz.timezone(user.timezone)).date()
                        #delete data back to last recorded time
                        if exist:
                            temp = user.weight.split(',')
                            for i in range(0,user.daysAbsent):
                                temp.pop()
                            user.weight = ','.join(temp)
                        #add data back to database
                        last = float(user.weight.split(",")[-1])
                        now = float(form1.todaysweight.data)
                        differenceEachDay = (now - last)/user.daysAbsent
                        for i in range(1,user.daysAbsent):
                            user.weight += "," + "%.2f"%(i * differenceEachDay + last)
                        user.weight += "," + "%.2f"%(float(form1.todaysweight.data))
                db.session.commit()
            #put user's information into achieve table if they achieve their target weight
            user = Weight.query.filter_by(email = session['email']).first()
            if user.target is not None:
                achieved = Achieved.query.filter_by(email = session['email']).first()
                begin = float(user.weight.split(",")[0])
                target = float(user.target)
                #requirement to be recorded: not in the least, reached the target, loss more than 10% of ur body weight
            if float(user.weight.split(",")[-1]) <= target and achieved == None and begin - target >= begin * 0.1:
                grats = Achieved(user.email, user.nickname, user.begindate,user.lastupdated,user.weight.split(",")[0],user.target)
                db.session.add(grats)
                db.session.commit()
            return redirect(url_for('profile'))

        #for edit form
        if form.submit.data and form.validate():
            weight = Weight.query.filter_by(email = session['email']).first()
            user = User.query.filter_by(email = session['email']).first()
            if form.nickname.data != '':
                if weight is not None:
                    weight.nickname = form.nickname.data
                user.nickname = form.nickname.data
            try:
                float(form.target.data)
                if weight is not None:
                    weight.target = form.target.data
                user.target = form.target.data
            except ValueError:
                pass
            if form.timezone.data != "default":
                user.timezone = form.timezone.data
                if weight is not None:
                    weight.timezone = form.timezone.data
            db.session.commit()
            return redirect(url_for('profile'))


        #for user process tracking form

        if form2.submit.data and form2.validate():
            
            number = ["filenumber","startweight","finishweight"]
            if form2.days.data in ["7","30"]:
                
                if makePicture(int(form2.days.data)) == True:

                    loss = number[1] - number[2]
                    if loss < 0:
                        message = "Seriously? are you really try to lose weight?"
                    else:
                        message = "You lose " + "%.2f"%(loss) + " Kg in " + form2.days.data + " days"

                    number = number[0]
                else:
                    number = [""]
                    warn = "Did you at least record twice during those days?"
            elif form2.days.data == "max":
                weight = Weight.query.filter_by(email = session['email']).first()
                days = (datetime.now(pytz.timezone(weight.timezone)).date() - weight.begindate).days + 1
                makePicture(days)
                
                loss = number[1] - number[2]
                if loss < 0:
                    message = "Seriously? are you really try to lose weight?"
                else:
                    
                    message = "You lose " + "%.2f"%(loss) + " Kg in " + str(len((Weight.query.filter_by(email = session['email']).first()).weight.split(","))) + " days"
                number = number[0]

    return render_template('profile.html',nickname = user.nickname,email = user.email,groupnameList = groupnameList, grouplist=grouplist, form = form, form1 = form1, form2 = form2, number = number, newuser = newuser, timezoneRecorded = timezoneRecorded, message = message, warn = warn)