简体   繁体   中英

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'?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM