【发布时间】:2019-09-02 15:36:24
【问题描述】:
我正在尝试使用 Flask 链接用户的帖子。 For instance, A user add a new product into the database from a form and it be displayed on its User template.
我不知道是否应该将帖子添加到由用户 ID 链接的数据库中,或者我只需要使用它的会话。
我在表单中使用了一个简单的函数将帖子插入到集合中,但我不知道是否需要改进以与会话用户链接?
app.py:
@app.route('/insert_product', methods=['POST'])
def insert_product():
products=mongo.db.products
products.insert_one(request.form.to_dict())
return redirect(url_for('index'))
用户模板:
<form class="text-center border border-light p-5" action="{{url_for('insert_product')}}" method='POST'>
<p class="h4 mb-4">Add a new product</p>
<div class="form-row mb-4">
<!-- Category -->
<select class="form-control " name="category_name">
<option disabled selected>Select Category</option>
{% for cat in category %}
<option value='{{cat.category_name}}'>{{cat.category_name}}</option>
{% endfor %}
</select>
</div>
<!-- Product Name -->
<input type="text" id="product_name" name="product_name" class="form-control mb-4" placeholder="Product Name" required>
<!-- Price -->
<input type="number" min="1" step="any" id="#" name="price" class="form-control mb-4" placeholder="Price" required>
<input type="text" id="url" name="url" class="form-control mb-4" placeholder="Add Image URL"> {% if session['email'] != None %}
<input type="text" id="seller" name="seller" class="form-control mb-4" placeholder="Seller Name" value="{{session['name']}}" required> {% endif %}
<div class="form-group green-border-focus">
<textarea class="form-control" id="product_description" name='product_description' placeholder="Add product description" rows="3" required></textarea>
</div>
<!-- Sign up button -->
<button class="btn btn-info my-4 btn-block" type="submit">Submit</button>
<hr>
<!-- Terms of service -->
<p>By clicking
<em>Sign up</em> you agree to our
<a href="" target="_blank">terms of service</a>
</form>
我能够显示帖子和所有其他 CRUD 功能。只是这个小问题我想知道以完成我的项目。谢谢。
【问题讨论】: