コード例 #1
0
ファイル: views.py プロジェクト: wduncanfraser/item_catalog
def item_new(category_id=None):
    """
    View for creating new item
    :param category_id: optional, id of category of new item
    :context form: Instance of :form:`item_catalog.ItemForm`
    :template: `item_edit.html`
    """
    # Check if user is logged in
    if not check_login(session):
        abort(403)

    if category_id:
        category = Category.query.get_or_404(category_id)
    else:
        category = None

    form = ItemForm()

    # If form is valid on post, populate model instance and save
    if form.validate_on_submit():
        item = Item()
        form.populate_obj(item)
        item.picture = None
        item.owner = User.query.get(session.get('user_id'))
        db.session.add(item)
        db.session.commit()

        # If there is picture data, let's save it now that we have an item id
        if form.picture.data:
            data = form.picture.data
            filename = secure_filename(data.filename)
            item_path = None
            try:
                item_path = save_uploaded_image(filename, data, item)
            except:
                abort(500)

            item.picture = item_path
            db.session.add(item)
            db.session.commit()

        flash("Successfully Created %s" % item.name, 'notice')
        return redirect(url_for('item_view', item_id=item.id))

    return render_template('item_edit.html', form=form, category=category)
コード例 #2
0
ファイル: views.py プロジェクト: wduncanfraser/item_catalog
def item_edit(item_id):
    """
    View for editing an existing item. Check if current user is owner. Aborts otherwise.
    :param item_id: id of requested item
    :context form: Instance of :form:`item_catalog.ItemForm`
    :context item: Instance of :model:`item_catalog.Item`
    :template: `item_edit.html`
    """
    item = Item.query.get_or_404(item_id)

    # Check if user is logged in and the item owner. Abort if either check fails
    if not check_login(session) or not is_item_owner(item, session.get('user_id')):
        abort(403)

    form = ItemForm(obj=item)

    if form.validate_on_submit():
        item_path = item.picture

        if form.picture.data:
            data = form.picture.data
            filename = secure_filename(data.filename)
            try:
                item_path = save_uploaded_image(filename, data, item)
            except:
                abort(500)

        form.populate_obj(item)
        item.picture = item_path
        item.edit_timestamp = datetime.utcnow()
        db.session.add(item)
        db.session.commit()
        flash("Successfully Saved %s" % item.name, 'notice')
        return redirect(url_for('item_view', item_id=item.id))

    return render_template('item_edit.html', form=form, item=item)