3

我有一个带有激活密钥( /user/activate/123123123 )的激活 URL。这没有任何问题。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)
4

1 回答 1

5

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

class ActivationView(FormView):
    # ...

    def get_initial(self):
        return {'key': self.kwargs['activation_key']}
于 2013-12-31T19:02:20.063 回答