4

I've got an activation url that carries the activation key ( /user/activate/123123123 ). That works without any issue. get_context_data can plop it into the template fine. What I want to do is have it as an initial value for the key field so the user only needs to enter username and password as created at registration.

How can I pull the key from context or get() without hardcoding the field into the template?

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)
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
meteorainer
  • 913
  • 8
  • 21

1 Answers1

5

You can override get_initial to provide dynamic initial arguments:

class ActivationView(FormView):
    # ...

    def get_initial(self):
        return {'key': self.kwargs['activation_key']}
sk1p
  • 6,645
  • 30
  • 35
  • That's exactly what I was looking for. Thanks. Where did you find get_intial? I was looking for a built in function that would do that and couldn't find anything documented. – meteorainer Dec 31 '13 at 19:33
  • 1
    For class based views, I always look at the source for reference. For this case, I looked at [views/generic/edit.py](https://github.com/django/django/blob/acd7b34aafe352ef604edcb73f75041c5cbba6b9/django/views/generic/edit.py#L22) – sk1p Dec 31 '13 at 19:37
  • I think I'm going to have to bookmark the source cause there are a LOT of helpers and built-ins that don't appear to be readily documented. Thanks again! – meteorainer Dec 31 '13 at 19:57