2016-03-04 113 views
0

我该如何处理来自listview模板的请求。如果我点击我的custom_list.html中的提交按钮,变量不会以字符串形式输出。我做错了什么 ?flask-admin处理请求正确方式

enter image description here

app.py

from flask import Flask 
import flask_admin as admin 
from flask_mongoengine import MongoEngine 
from flask_admin.contrib.mongoengine import ModelView 
from flask_admin.actions import action 

# Create application 
app = Flask(__name__) 

# Create dummy secrey key so we can use sessions 
app.config['SECRET_KEY'] = '123456790' 
app.config['MONGODB_SETTINGS'] = {'DB': 'test_app'} 

# Create models 
db = MongoEngine() 
db.init_app(app) 


class Website(db.Document): 
    domain_name = db.StringField(max_length=200) 
    title = db.StringField(max_length=160) 
    meta_desc = db.StringField() 


class WebsiteView(ModelView): 

    list_template = 'custom_list.html' 

    @action('create_meta', 'Create Meta', 'Are you sure you want to create meta data?') 
    def action_createmeta(self, ids): 

     print "this is my domain_name {} and this is my title {}".format(
      Website.domain_name, Website.title) 


# Flask views 
@app.route('/') 
def index(): 
    return '<a href="/admin/">Click me to get to Admin!</a>' 


if __name__ == '__main__': 
    # Create admin 
    admin = admin.Admin(app, 'Example: MongoEngine') 

    # Add views 
    admin.add_view(WebsiteView(Website)) 

    # Start app 
    app.run(debug=True) 

模板/ custom_list.html

{% extends 'admin/model/list.html' %} 
{% block body %} 
    <h1>Custom List View</h1> 
    {{ super() }} 
{% endblock %} 

{% block list_row_actions %} 
    {{ super() }} 

    <form class="icon" method="POST" action="/admin/website/action/"> 
    <input id="action" name="action" value="create_meta" type="hidden"> 
    <input name="rowid" value="{{ get_pk_value(row) }}" type="hidden"> 
    <button onclick="return confirm('Are you sure you want to create meta data?');" title="Create Meta"> 
     <span class="fa fa-ok icon-ok"></span> 
    </button> 
    </form> 
{% endblock %} 

输出

enter image description here

回答

1

您正在打印Website.domain_name的定义而不是值。

documentationexample你需要做的:

for id in ids: 
    found_object = Website.objects.get(id=id) 
    print "this is my domain_name {} and this is my title {}".format(
      found_object.domain_name, found_object.title) 

编辑:原职。

Change the line

print "this is my domain_name {} and this is my title {}".format(
     Website.domain_name, Website.title) 

to

print "this is my domain_name {} and this is my title {}".format(
     Website.domain_name.data, Website.title.data) 

You are printing the objects not the posted data contained within them

+0

时这样做,我得到一个错误:AttributeError的:“StringField”对象有没有属性“数据” – mvmthecreator

+0

尝试改变'Website.domain_name'等为'self.domain_name'。这样你就可以使用从Website继承的WebsiteView类实例化对象。我确实相信这是你的发布数据是 –

+0

之前已经尝试过的地方。得到另一个错误:AttributeError:'WebsiteView'对象没有属性'domain_name'。当我把.data放在后面我得到相同的错误 – mvmthecreator