Skip to content Skip to sidebar Skip to footer

How To Pass Username Into Function Inside A Form In Django?

I have a form which has a variable that calls a function to get a list of names. I need to pass the current logged in user as a dynamic parameter variable into this function. I hav

Solution 1:

Forms by itself doesn't have access to request object and therefore can't identify which user is currently logged. Your view should pass current user username instead:

views.py:

defindex(request):
    # ...
    form = ManagerForm(request.POST orNone, current_user_username=request.user.username)
    # ...

forms.py:

defget_employee_names(username):
    # assuming it constructs correct choices tuples, like:# choices = ((username, username), ('noname', 'noname'))return choices

classManagerForm(forms.Form):
    manager = forms.ChoiceField(choices=[], widget=forms.RadioSelect)

    def__init__(self, *args, **kwargs):
        username = kwargs.pop('current_user_username')
        super().__init__(*args, **kwargs)
        self.fields['manager'].choices = get_employee_names(username)

This is description of what django expect choices to be.

Post a Comment for "How To Pass Username Into Function Inside A Form In Django?"