Пример #1
0
def update_entry(entry_id):
    entry = Entry.query.get(entry_id)
    user = User.query.get(current_user.id)
    if request.method == 'DELETE':
        if entry.user_id == current_user.id:
            db.session.delete(entry)
            db.session.commit()
            return 'Deleted Entry'
        else:
            return 'Error: could not delete'

    elif request.method == 'PUT':
        if entry.user_id == current_user.id:
            form = EntryForm()
            form['csrf_token'].data = request.cookies['csrf_token']
            if form.validate_on_submit():
                if form.data['body_weight']:
                    entry.body_weight = form.data['body_weight']
                if form.data['bench_press']:
                    entry.bench_press = form.data['bench_press']
                if form.data['squat']:
                    entry.squat = form.data['squat']
                if form.data['deadlift']:
                    entry.deadlift = form.data['deadlift']
                if form.data['created_at']:
                    entry.created_at = form.data['created_at']
                db.session.add(entry)
                db.session.commit()
                return entry.to_dict()
            return {'errors': validation_errors_to_error_messages(form.errors)}
        else:
            return 'Error: could not delete'
Пример #2
0
    def edit(request,entry_id):
        """Renders the entry edit page."""
        assert isinstance(request, HttpRequest)
        try:
            entry = Entry.objects.get(pk=entry_id)
        except Entry.DoesNotExist:
            raise Http404("指定されたブログが存在しません。")
        if not request.user or request.user.pk != entry.member.pk:      # ブログ作成者以外は編集できない
            return HttpResponseForbidden()                              #アドレスをコピペしなければ通常は起こらないため例外処理で済ませておく。

        if request.method == 'POST': # フォームが提出された
            form = EntryForm(request.POST, instance = entry) # POST データの束縛フォーム
            if form.is_valid(): # バリデーションを通った
                form.save()
                return HttpResponseRedirect(reverse('entry_list')) # POST 後のリダイレクト
        else:
            form = EntryForm(instance = entry) # 非束縛フォーム
        article_list = Article.objects.order_by('-released_at')[:5]
        return render(request, 'app/entry_edit.html', { 
            'form': form,
            'title':'ブログ記事の編集',
            'year':datetime.now().year,
            'articles':article_list,
            'blogs':EntryView.get_entry_list('-posted_at',-1, request.user.pk )[:5],
            'submit_title':'更新',
            'entry_pk':entry.pk,
            'current_user':request.user,
        })
Пример #3
0
def update_entry(id):
    form = EntryForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        # content = request.json
        entry_update = Entry.query.get(id),
        entry_update.body = form.data['body'],
        entry_update.category_id = form.data['category_id']

        db.session.add(entry_update)
        db.session.commit()
        return entry_update.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}
Пример #4
0
def new_task():
    form = EntryForm()
    if form.validate_on_submit():
        new_post = PostForm(title=form.title.data,
                            category=form.category.data,
                            task=form.task.data)
        db.session.add(new_post)
        db.session.commit()
        flash('Task added to ToDo List', 'success')
        return redirect(url_for('index'))
    path = request.path
    return render_template('new_task.html',
                           title='Add Task',
                           form=form,
                           path=path)
Пример #5
0
def created_entry():
    form = EntryForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        # content = request.json
        new_entry = Entry(
            body = form.data['body'],
            date = datetime.datetime.now(),
            page_layout = form.data['page_layout'],
            user = current_user,
            journal_id = form.data['journal_id'],
            category_id = form.data['category_id']
        )
        db.session.add(new_entry)
        db.session.commit()
        return new_entry.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}
Пример #6
0
def create_entry():
    user = User.query.get(current_user.id)
    form = EntryForm()
    form['csrf_token'].data = request.cookies['csrf_token']

    if form.validate_on_submit():
        entry = Entry(
            user_id=user.id,
            body_weight=form.data['body_weight'],
            bench_press=form.data['bench_press'],
            squat=form.data['squat'],
            deadlift=form.data['deadlift'],
            created_at=form.data['created_at'],
        )
        db.session.add(entry)
        db.session.commit()
        return entry.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}
Пример #7
0
def add():
    form = EntryForm()
    #print(form.validate_on_submit())
    if form.validate_on_submit():
        #g.book.name = form.name.data
        #g.book.author = form.author.data
        u = books(name = form.name.data,    \
                 author = form.author.data, \
                 age = form.age.data,       \
                 public = form.public.data, \
                 home = form.home.data,     \
                 pages = form.pages.data)
        db.session.add(u)
        db.session.commit()
        #print(u)
        flash('new item added!')
        return redirect('/index')
    else :
        return render_template("edit.html", form = form)
Пример #8
0
def add():
    form = EntryForm()
    #print(form.validate_on_submit())
    if form.validate_on_submit():
        #g.book.name = form.name.data
        #g.book.author = form.author.data
        u = books(name = form.name.data,    \
                 author = form.author.data, \
                 age = form.age.data,       \
                 public = form.public.data, \
                 home = form.home.data,     \
                 pages = form.pages.data)
        db.session.add(u)
        db.session.commit()
        #print(u)
        flash('new item added!')
        return redirect('/index')
    else:
        return render_template("edit.html", form=form)
Пример #9
0
def new_entry(req, id):
    if req.method == 'POST':
        form = EntryForm(req.POST)

        if form.is_valid():
            tmp = get_object_or_404(Trip, id=id)
            a = Entry(date=form.cleaned_data['date'],
                      content=form.cleaned_data['content'],
                      traveller=req.user,
                      trip=tmp)
            a.save()
            return redirect('app:trip_entries', id)
        else:
            return render(req, 'entry/new_entry.html', {
                'form': form,
                'id': id
            })
    else:
        form = EntryForm()
        return render(req, 'entry/new_entry.html', {'form': form, 'id': id})
Пример #10
0
def entry():
    print("You are in entry now")
    dateString = datetime.now().strftime("%d-%b-%Y")
    team_roster = current_user.athlete_userids[1:-1].split(
        ","
    )  #Take the athlete_userids string and split it into a list of athletes
    athlete_names = [(i, i) for i in team_roster]
    exercise_names = Exercise.get_names()
    form = EntryForm(exercise_names, athlete_names)

    if form.validate_on_submit():
        ex_name = form.exercise_name.data
        athlete_id = form.athlete_id.data.lstrip(
            ' ')  #strips leading whitespaces from athlete_id
        return redirect(
            url_for('second', exercise_name=ex_name, athlete_id=athlete_id))
    return render_template('entry.html',
                           title="Exercise Entry Form",
                           date=dateString,
                           form=form)
Пример #11
0
def add(request):
    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Entry was successfully added!')
            return redirect('index')
    else:
        form = EntryForm()
    return render(request, 'app/entry.html', {'form': form})
Пример #12
0
def edit(request, entry_id):
    entry = get_object_or_404(Entry, pk=entry_id)
    if request.method == 'POST':
        form = EntryForm(request.POST, instance=entry)
        if form.is_valid():
            form.save()
            messages.success(request, 'Entry was successfully edited!')
            return redirect('index')
    else:
        form = EntryForm(instance=entry)
    return render(request, 'app/entry.html', {'form': form})
Пример #13
0
def modify(post_id):
    form = EntryForm()
    mod_post = PostForm.query.get(post_id)
    if form.validate_on_submit():
        mod_post.title = form.title.data
        mod_post.category = form.category.data
        mod_post.task = form.task.data
        db.session.commit()
        flash('ToDo List was Modified', 'success')
        return redirect(url_for('index'))
    else:
        if not mod_post:
            flash('No post with that ID', 'warning')
            return redirect(url_for('index'))
        else:
            form.title.data = mod_post.title
            form.category.data = mod_post.category
            form.task.data = mod_post.task
            return render_template('modify.html',
                                   title='Modify Task',
                                   form=form,
                                   post_id=post_id)
Пример #14
0
def edit_entry(req, trip_id, entry_id):
    if req.method == 'POST':
        form = EntryForm(req.POST)

        if form.is_valid():
            e = Entry.objects.get(id=entry_id)
            e.date = form.cleaned_data['date']
            e.content = form.cleaned_data['content']
            e.save()
            return redirect('app:trip_entries', trip_id)
        else:
            return render(req, 'edit_entry.html', {
                'form': form,
                'trip_id': trip_id,
                'entry_id': entry_id
            })
    else:
        e = Entry.objects.get(id=entry_id)
        form = EntryForm(instance=e)
        return render(req, 'edit_entry.html', {
            'form': form,
            'trip_id': trip_id,
            'entry_id': entry_id
        })
Пример #15
0
 def new(request):
     """Renders the new entry page."""
     assert isinstance(request, HttpRequest)
     if request.method == 'POST': # フォームが提出された
         form = EntryForm(request.POST) # POST データの束縛フォーム
         if form.is_valid(): # バリデーションを通った
             entry = form.save(commit=False)
             entry.member = request.user
             entry.save()
             return HttpResponseRedirect(reverse('entry_list')) # POST 後のリダイレクト
     else:
         form = EntryForm() # 非束縛フォーム
     article_list = Article.objects.order_by('-released_at')[:5]
     auth_form = AuthenticationForm(None, request.POST or None)
     return render(request, 'app/entry_edit.html', { 
         'form': form,
         'title':'ブログ記事の新規登録',
         'year':datetime.now().year,
         'articles':article_list,
         'blogs':EntryView.get_entry_list('-posted_at',-1, request.user.pk )[:5],
         'submit_title':'登録する',
         'auth_form':auth_form,
         'current_user':request.user,
     })
Пример #16
0
def index():

    #parseData(db, 'cc_sample.csv', 'Credit Card')
    #parseData(db, 'mm_sample.csv', 'Money Market')
    #parseData(db, 'check_sample.csv', 'Checking')
    entries = Entry.query.all()
    #print(entries[0].description)
    #print(entries[1].description)

    form = EntryForm()

    accountList = [
        ('0', 'Money Market'), ('1', 'Credit Card'), ('2', 'Checking')
    ]  # id must be a str? else validate_on_submit will be False? why or use coerce=int?
    form.accountType.choices = accountList

    if request.method == 'GET':
        print('GET')
    elif request.method == 'POST':
        print('POST')
        #if form.validate_on_submit():  # do i need this?
        if form.backup.data:
            print('EXPORT DATA:')
            backupData(db)

        elif form.restore.data:
            print('IMPORT DATA:')
            restoreData(db)

        elif form.submit.data:
            print('Upload DATA:')
            # do this instead?  https://flask-wtf.readthedocs.io/en/stable/form.html#module-flask_wtf.file

            # TODO create a route to handle the upload/parse
            # check if the post request has the file part
            if 'file' not in request.files:  # file or files?
                flash('No file part')
                return redirect(request.url)
            file = request.files['file']

            # if user does not select file, browser also
            # submit an empty part without filename
            if file.filename == '':
                flash('No selected file')
                return redirect(request.url)
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)

                # save the file from ?the browser's cache? to a known dir so that it can be read
                # the file object, werkzeug.FileStorage, does not have the full path or ?knows it?
                file.save(os.path.join(Config.UPLOAD_FOLDER, filename))

                print('file:', filename, form.accountType.data)
                filename = '%s/%s' % (Config.UPLOAD_FOLDER, filename)
                if int(form.accountType.data) == 0:
                    parseData(db, filename, 'Money Market')
                elif int(form.accountType.data) == 1:
                    parseData(db, filename, 'Credit Card')
                elif int(form.accountType.data) == 2:
                    parseData(db, filename, 'Checking')
                return redirect('/')

    return render_template('index.html',
                           title='Home',
                           form=form,
                           entries=entries)