【问题标题】:UpdateView unable to process POST request - form is not callable?UpdateView 无法处理 POST 请求 - 表单不可调用?
【发布时间】:2018-07-25 17:25:09
【问题描述】:

根据 UpdateView 上的文档,这应该非常简单,并且表单确实显示了数据库中的内容,但是当单击提交按钮时,django 会显示一条消息:

'ProfileForm' object is not callable'. 

为什么它需要一个可调用的表单?例如,该表单与 CreateView 配合得很好,所以那里没有问题,现在不明白为什么它会抱怨。

我研究了 stackoverflow 并在 google 上搜索,确实有结果,但它们似乎都不适用于我的情况,因为我没有看到我犯了任何错误,尽管显然我显然是根据 django 的。

我的代码如下:

class PortfolioEditBase(UpdateView):
    post_req = False
    url_name = ''

    def form_valid(self, form):
        self.post_req = True
        return super(PortfolioEditBase, self).get_form(form)

    def get_context_data(self, **kwargs):
        context = super(PortfolioEditBase, self).get_context_data(**kwargs)
        context['post_req'] = self.post_req
        context['profile_id'] = self.kwargs['profile_id']
        return context

    def get_success_url(self):
        return reverse(self.url_name, args=self.kwargs['profile_id'])


class PortfolioEditGeneralInfo(PortfolioEditBase):
    model = Profile
    form_class = ProfileForm
    url_name = 'plan:general-info-edit'
    template_name = 'plan/portfolio/edit/general_info_edit.html'

个人资料表格有以下代码:

class ProfileForm(ModelForm):
  class Meta:
    model = Profile
    fields = ['company', 'exchange', 'ticker',
              'investment_stage', 'investment_type']
    widgets = {
      'earnings_growth': Textarea(attrs={'cols': 1, 'rows': 2}),
    }

这是相关的urls.py代码:

url(r'^portfolio/general-info/edit/(?P<profile_id>[0-9]+)$', views.PortfolioEditGeneralInfo.as_view(), name='general-info-edit'),

我认为 django 给我的错误信息没有任何意义。如何提供一条错误消息,详细说明实际问题是什么。使用基于函数的视图非常简单,只需几行代码即可使用,但基于类的视图被认为是“最佳实践”。它似乎试图获取表单数据,但我不明白为什么它会有任何问题,以及为什么它会调用 from 而不是使用 request.POST 获取数据。

有人知道这里有什么问题吗?当它假设如此简单时,这很烦人。使用的其他基于类的视图几乎没有任何问题。

【问题讨论】:

    标签: python django django-views django-class-based-views


    【解决方案1】:

    form_valid 方法中的错误。应该是form_vaild 而不是get_form

    def form_valid(self, form):
        self.post_req = True
        return super(PortfolioEditBase, self).form_valid(form)
    

    get_form 方法期望表单类作为参数。但是您正在传递表单实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      相关资源
      最近更新 更多