2013-09-23 85 views
1

我試圖根據用戶權限更新選擇字段。我有一個布爾字段,如果False(默認)標準用戶可以看到。否則,如果用戶有權限,我想顯示所有內容。從數據庫填充Django選擇字段基於user.has_perms

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 

任何幫助將不勝感激,我一直堅持這個爲一個whil現在(並嘗試了許多谷歌搜索建議/答案。)

回答

1

找到了如何做到這一點,仍然對其他方式感興趣。

使用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) 
+0

另一參考文獻[http://ilian.ini.org/django-forms- choicefield-與動態值/(http://ilian.ini.org/django-forms-choicefield-with-dynamic-values/)。 – santiagopim

相關問題