【问题标题】:Django: How to pre-populate FormView with dynamic (non-model) data?Django:如何使用动态(非模型)数据预填充 FormView?
【发布时间】:2014-03-31 18:00:20
【问题描述】:

我有一个 FormView 视图,使用 get_context_data() 提供了一些额外的 GET 上下文:

class SignUpView(FormView):
    template_name = 'pages_fixed/accounts/signup.html'
    form_class = SignUpForm

    def get_context_data(self, **kwargs):
        context = super(SignUpView, self).get_context_data(**kwargs)
        context = {
            'plans':    common.plans,
            'pricing':  common.pricing,
        }
        return context

这很好用。但是,我在会话中也有一些值(不是来自任何绑定模型),我想将它们预填充到表单中。这些根据用户在前一页上的操作而有所不同。我知道(从我的另一个 post 那里)我可以将表单传递到上下文中(使用 initial=)但是在上面的 FormView 情况下是否有可能?

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    您可以覆盖 FormView 类的“get_initial”方法。请参阅here 了解更多信息,

    例如

    def get_initial(self):
        """
        Returns the initial data to use for forms on this view.
        """
        initial = super().get_initial()
    
        initial['my_form_field1'] = self.request.something
    
        return initial
    

    'get_initial' 应该返回一个字典,其中键是表单上字段的名称,值是向用户显示表单时要使用的初始值。

    【讨论】:

    • 谢谢!当然看起来它应该可以工作,但没有任何结果——表单仍然是空白的(我有缩进的返回)。我仔细检查了表单字段键和会话值都很好。有什么我可能还缺少的吗?
    • @pete 尝试首先从 super() 获取初始数据,而不是使用要更新的字段及其值更新字典并返回。这应该工作
    • 是的,我的“返回”没有正确缩进。我又更新了ans。
    • 不喜欢退货。获得global name 'intitial' is not defined'SignUpView' object has no attribute 'intitial'(当我尝试时:返回self.initial)
    • 检查initial的拼写。
    猜你喜欢
    • 2014-02-14
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2017-07-23
    • 2012-10-03
    • 1970-01-01
    相关资源
    最近更新 更多