GrantU
GrantU

Reputation: 6555

Django How to pre-populate a form field with a argument form context

I have the following view below. I would like to use 'email' from the get_context_data method to pre-populate a form field in my UserAuthenticationForm form, how is this possible?

View:

class CampaignLoginView(LoginView):
    model = Campaign
    form_class = UserAuthenticationForm


    def get_context_data(self, *args, **kwargs):
        context = super(CampaignLoginView, self).get_context_data(*args, **kwargs)
        user = AppUser.objects.get(pk=1)
        context['email'] = user.email  

Form:

class UserAuthenticationForm(AuthenticationForm):

    def __init__(self, *args, **kwargs):
        super(UserAuthenticationForm, self).__init__(*args, **kwargs)

Or is there is a way 'I should be doing it'?

Upvotes: 1

Views: 1094

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

What you want to do is pass initial data to the form. Assuming that LoginView is a class-based view that includes the FormMixin, this is best done in the get_form_kwargs method:

def get_form_kwargs(self):
    kwargs = super(CampaignLoginView, self).get_form_kwargs()
    kwargs['initial']['email'] = self.request.user.email
    return kwargs

Upvotes: 2

Related Questions