【问题标题】:Setting initial formfield value from context data in Django class based view在基于 Django 类的视图中从上下文数据中设置初始表单字段值
【发布时间】:2013-12-31 17:37:14
【问题描述】:

我有一个带有激活密钥的激活 URL ( /user/activate/123123123 )。这没有任何问题。 get_context_data 可以很好地将其放入模板中。我想要做的是将它作为键字段的初始值,因此用户只需要输入注册时创建的用户名和密码。

如何在不将字段硬编码到模板中的情况下从上下文或 get() 中提取密钥?

class ActivateView(FormView):
    template_name = 'activate.html'
    form_class = ActivationForm
    #initial={'key': '123123123'} <-- this works, but is useless

    success_url = 'profile'

    def get_context_data(self, **kwargs):
        if 'activation_key' in self.kwargs:
            context = super(ActivateView, self).get_context_data(**kwargs)
            context['activation_key'] = self.kwargs['activation_key']
            """
            This is what I would expect to set the value for me. But it doesn't seem to work.
            The above context works fine, but then I would have to manually build the 
            form in the  template which is very unDjango.
            """
            self.initial['key'] = self.kwargs['activation_key']  
            return context
        else:
            return super(ActivateView, self).get_context_data(**kwargs)

【问题讨论】:

    标签: django forms django-context


    【解决方案1】:

    您可以覆盖get_initial 以提供动态初始参数:

    class ActivationView(FormView):
        # ...
    
        def get_initial(self):
            return {'key': self.kwargs['activation_key']}
    

    【讨论】:

    • 这正是我想要的。谢谢。您在哪里找到 get_initial?我正在寻找一个可以做到这一点的内置函数,但找不到任何文档。
    • 对于基于类的视图,我总是查看源代码以供参考。对于这种情况,我查看了views/generic/edit.py
    • 我想我将不得不为源代码添加书签,因为有很多帮助程序和内置插件似乎不容易记录。再次感谢!
    猜你喜欢
    • 2013-06-26
    • 2012-07-30
    • 2013-12-03
    • 2015-07-19
    • 2012-06-21
    • 2014-04-18
    • 2010-10-23
    • 2021-08-14
    • 2018-05-06
    相关资源
    最近更新 更多