Skip to main content
 首页 » 编程设计

python之根据 user.has_perms 从数据库填充 Django Choice 字段

2024年11月01日28wayfarer

我正在尝试根据用户权限更新选择字段。我有一个 bool 字段,如果为 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 

表单.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 

任何帮助将不胜感激,我已经坚持了一段时间(并尝试了许多谷歌搜索的 SO 建议/答案。)

请您参考如下方法:

找到了如何去做,仍然对其他方式感兴趣。

使用 pdb,我发现 View 设置正确。但我不得不改变形式。我无法从 __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 

表单.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)