Passing **kwargs to Django Form

后端 未结 2 462
忘了有多久
忘了有多久 2021-01-31 17:05

I am trying to build custom django form for changing username and user email for an application. That\'s why I need to pass the user details from the session to a form in order

2条回答
  •  礼貌的吻别
    2021-01-31 17:24

    user_details is passed to __init__, so is not defined outside of it. That's why you can't access it when you're instatiating that CharField object. Set initial in __init__ itself, after you've popped it from kwargs, for instance:

    class PersonalInfoForm(forms.Form):
    
        username = forms.CharField(required=True)
        email = forms.EmailField(required=True)
    
        def __init__(self, *args, **kwargs):
            user_details = kwargs.pop('user_details', None)
            super(PersonalInfoForm, self).__init__(*args, **kwargs)
            if user_details:
                self.fields['username'].initial = user_details[0]['username']
    

    When you get a chance, consider reading up on scopes in python.

提交回复
热议问题