python - 如何将用户名传递给django表单内的函数?
问题描述
我有一个表单,它有一个调用函数来获取名称列表的变量。我需要将当前登录的用户作为动态参数变量传递给这个函数。
我花了大约 2 天的时间来尝试尽我所能解决的所有问题。找不到任何有效的东西。我试图初始化一个请求对象,但无法让它工作。
class ManagerForm(forms.Form):
names = get_employee_names(<<dynamic username goes here>>)
manager = forms.ChoiceField(choices=names, widget=forms.RadioSelect)
预期的结果是将用户名作为字符串作为参数传递给函数。
解决方案
表单本身无权访问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)
推荐阅读
- shell - 如何在 Windows git bash 中从插入模式更改为命令模式
- visual-studio-2015 - 如何区分 exe 与 VS15 编译或 VS17 编译
- concourse - 大厅的 msbuild 资源类型
- java - 用于 jakartaee restful jpa Web 应用程序的 docker-compose 不工作
- c - 我无法理解 read 系统调用的作用
- reactjs - 纱线版本 2 的 Storybook 5.3 问题
- php - 在项目中使用 Git.php
- javascript - 测试 preact-router 的路由能力
- websocket - Janus 网关在音频呼叫网络应用程序中的位置
- android - 如何将 Couchbase 与 couchbase lite 版本 2.7 连接?