質問

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)
役に立ちましたか?

解決

You can override get_initial to provide dynamic initial arguments:

class ActivationView(FormView):
    # ...

    def get_initial(self):
        return {'key': self.kwargs['activation_key']}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top