【问题标题】:Migrating method views to class based views with TemplateView使用 TemplateView 将方法视图迁移到基于类的视图
【发布时间】:2013-04-15 22:47:26
【问题描述】:

在 Django 1.4 及之前的版本中,我的视图如下所示:

def myview(request, item_id):
    item = get_object_or_404(Item, item_id)

    if request.method == "GET":
        return direct_to_template(request, "template.html", 
            { 'form': ItemForm() })
    elif request.method == "POST":
        form = ItemForm(request.POST)

        if form.is_valid():
            return redirect("/")
        else:
            return direct_to_template(request, "template.html",
                { 'form': form })

我想重写它以与使用 TemplateView 的 Django 新的基于类的视图系统兼容,但我不确定如何实现这些方法。如何迁移到使用 TemplateView 子类来实现 POST 和 GET?

【问题讨论】:

    标签: django django-1.5


    【解决方案1】:

    您可能想使用FormView

    class ItemFormView(FormView):
        template_name = 'template.html'
        form_class = ItemForm
        success_url = '/'
    

    【讨论】:

    • 课堂上实际的交互性怎么写?
    • 你想要什么样的“互动”?
    • 同上。如何编写我的get() 方法和我的post() 方法?
    • 我建议您阅读链接的文档。 FormView 继承自 FormMixinProcessFormView,并自行处理获取和发布功能。如果您想在已经提供的方法之上编写自己的 get 和 post 方法,您只需编写它们。这些方法称为get 和post。您也可以查看the source code了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多