Setting initial formfield value from context data in Django class based view
Asked Answered
B

1

6

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)
Blume answered 31/12, 2013 at 17:37 Comment(0)
S
8

You can override get_initial to provide dynamic initial arguments:

class ActivationView(FormView):
    # ...

    def get_initial(self):
        return {'key': self.kwargs['activation_key']}
Shortlived answered 31/12, 2013 at 19:2 Comment(3)
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.Blume
For class based views, I always look at the source for reference. For this case, I looked at views/generic/edit.pyShortlived
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!Blume

© 2022 - 2024 — McMap. All rights reserved.