如何将值传递给可插入视图?

时间:2013-02-26 15:09:10

标签: python-2.7 flask

我正在尝试实现一个模板,用于添加带可插入视图的VIEW,ADD和EDIT网页。我如何使用类似的网址值?

这是我试图转换为可插入视图的代码。

@app.route('/edit/category/<category>', methods=['GET', 'POST'])
def editCategory(category):
    form = forms.AddCategory()
    form.name.data = category
    if form.validate_on_submit():
        newName = form.name.data
        database.editCategory(name = category, newName = newName)
        #view single category?
        return redirect('/view/categories/')
    return render_template('edit-category.html', category = category, form = form)

可插入查看代码

class ListView(View):

    def getTemplate_name(self):
        raise NotImplementedError()

    def render_template(self, context):
        return render_template(self.get_template_name(), **context)

    def dispatch_request(self):
        context = self.get_context()
        return self.render_template(context)

class CategoryView(ListView):

    def get_template_name(self):
        return 'categories.html'

    def get_objects(self):
        return models.Category.query.all()

    def get_form(self):
        return forms.AddCategory()

    def get_context(self):
        return {'categories': self.get_objects(), 'form': self.get_form()}

app.add_url_rule('/view/categories', view_func=CategoryView.as_view('category'))

class EditCategory(ListView):

    def get_template_name(self):
        return 'edit-category.html'

    def get_form(self, category):
        form = forms.AddCategory()
        form.name.data = category
        return form

    def get_context(self):
        return {'form': self.get_form()}

app.add_url_rule('/edit/category/<category>', view_func=EditCategory.as_view('category'))

1 个答案:

答案 0 :(得分:0)

您需要覆盖dispatch_request类中的EditCategory方法,因为此方法已将url值传递给它。

class EditCategory(View):

    ...

    def get_context(self, category):
        return {'form': self.get_form(category)}

    def dispatch_request(self, category):
        context = self.get_context(category)
        return self.render_template(context)

app.add_url_rule('/edit/category/<category>', view_func=EditCategory.as_view('category'))

顺便说一句,我认为你最好使用原始的装饰视图函数,在这种情况下,viewCategoryeditCategory功能之间的共性很少