In one of the template pages of my Django app, the page asks for the user to select the choices he wants, from a checkbox list.
在我的Django应用程序的一个模板页面中,该页面要求用户从复选框列表中选择他想要的选项。
The catch is, that there are different choices for different users (for example, based on their past interests, there are different options).
问题是,不同的用户有不同的选择(例如,根据他们过去的兴趣,有不同的选择)。
How do you generate Django forms with CheckboxSelectMultiple()
fields that generate custom choices for each user?
如何使用CheckboxSelectMultiple()字段生成Django表单,这些字段为每个用户生成自定义选择?
1 个解决方案
#1
1
In forms.py you need to override the __init__
method, and set there the choices passed from the view when you call the form class.
在形式。py需要重写__init__方法,并设置在调用表单类时从视图传递的选项。
Here is an example:
这是一个例子:
class UserOptionsForm(forms.Form):
user_personal_options = forms.ChoiceField(choices=(),
widget=forms.CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
choices = kwargs.pop('choices', None) # return the choices or None
super(UserOptionsForm, self).__init__(*args, **kwargs)
if choices is not None:
self.fields['user_personal_options'].choices = choices
So in your view:
在你的观点:
def user_options(request, user_id):
if request.method == 'POST':
form = UserOptionsForm(request.POST)
if form.is_valid():
# proccess form data here
form.save()
else:
# render the form with user personal choices
user_choices = [] # do shometing here to make the choices dict by user_id
form = UserOptionsForm(choices=user_choices)
#1
1
In forms.py you need to override the __init__
method, and set there the choices passed from the view when you call the form class.
在形式。py需要重写__init__方法,并设置在调用表单类时从视图传递的选项。
Here is an example:
这是一个例子:
class UserOptionsForm(forms.Form):
user_personal_options = forms.ChoiceField(choices=(),
widget=forms.CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
choices = kwargs.pop('choices', None) # return the choices or None
super(UserOptionsForm, self).__init__(*args, **kwargs)
if choices is not None:
self.fields['user_personal_options'].choices = choices
So in your view:
在你的观点:
def user_options(request, user_id):
if request.method == 'POST':
form = UserOptionsForm(request.POST)
if form.is_valid():
# proccess form data here
form.save()
else:
# render the form with user personal choices
user_choices = [] # do shometing here to make the choices dict by user_id
form = UserOptionsForm(choices=user_choices)