首页 > 解决方案 > 如何将用户名传递给django表单内的函数?

问题描述

我有一个表单,它有一个调用函数来获取名称列表的变量。我需要将当前登录的用户作为动态参数变量传递给这个函数。

我花了大约 2 天的时间来尝试尽我所能解决的所有问题。找不到任何有效的东西。我试图初始化一个请求对象,但无法让它工作。

class ManagerForm(forms.Form):
    names = get_employee_names(<<dynamic username goes here>>)
    manager = forms.ChoiceField(choices=names, widget=forms.RadioSelect)

预期的结果是将用户名作为字符串作为参数传递给函数。

标签: pythondjango

解决方案


表单本身无权访问request对象,因此无法识别当前登录的用户。您的视图应该传递当前用户用户名:

视图.py:

def index(request):
    # ...
    form = ManagerForm(request.POST or None, current_user_username=request.user.username)
    # ...

表格.py:

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

class ManagerForm(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)

这是对 django 期望的choices描述


推荐阅读