我正在尝试根据用户权限更新选择字段。我有一个布尔字段,如果标准用户看到False(默认)。否则,如果用户拥有该权限,我想显示所有内容。
views.py
class ExportFormView(FormView):
template_name = 'export.html'
form_class = ExportForm
success_url = '/'
def get_form_kwargs(self):
kwargs = super(ExportFormView, self).get_form_kwargs()
kwargs.update({
'request' : self.request
})
return kwargs
forms.py
class ExportForm(forms.Form):
def __init__(self, request, *args, **kwargs):
self.request = request
super(ExportForm, self).__init__(*args, **kwargs)
choice_list = []
if request.user.has_perms('tracker.print_all'):
e = Muid.objects.values('batch_number').distinct()
else:
e = Muid.objects.values('batch_number').distinct().filter(printed=False)
for item in e:
choice = item['batch_number']
choice_list.append((choice, choice))
batch_number = forms.ChoiceField(choices = choice_list)
我得到错误:
NameError at /
name 'request' is not defined
任何帮助将不胜感激,我已经坚持了一段时间了(并尝试了很多google搜索SO建议/答案。)
答案 0 :(得分:2)
了解如何做到这一点,仍然对其他方式感兴趣。
使用pdb,我发现视图设置正确。但我不得不改变形式。我无法从函数外部访问变量,如__init__,其他函数也应该能够访问变量,但我需要在init上创建表单,所以我不能等待函数调用。
代码:
<强> Views.py 强>
class ExportFormView(FormView):
template_name = 'export_muids.html'
form_class = ExportForm
success_url = '/'
def get_form_kwargs(self):
kwargs = super(ExportFormView, self).get_form_kwargs()
kwargs.update({
'request' : self.request
})
return kwargs
<强> forms.py 强>
class ExportForm(forms.Form):
def __init__(self, request, *args, **kwargs):
self.request = request
choice_list = []
if request.user.has_perms('tracker.print_all'):
e = Muid.objects.values('batch_number').distinct()
else:
e = Muid.objects.values('batch_number').distinct().filter(exported=False)
for item in e:
choice = item['batch_number']
choice_list.append((choice, choice))
super(ExportForm, self).__init__(*args, **kwargs)
self.fields['batch_number'] = forms.ChoiceField(choices = choice_list)