在基于Django类的视图中从上下文数据设置初始formfield值

时间:2013-12-31 17:37:15

标签: django forms django-context

我有一个带有激活密钥的激活网址(/ 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)

1 个答案:

答案 0 :(得分:3)

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

class ActivationView(FormView):
    # ...

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