Django:访问request.GET表单以将queryset作为选项传递

时间:2016-02-29 10:12:19

标签: python django forms choicefield

如何在Django中访问表单中的requset? 我需要这个来获取数据元组以传递选择形式。 init 方法下方不起作用: NameError:名称'请求'未定义,自我或不包含: self.request.GET.get('project ') request.GET.get('project')

class PostfilterForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(PostfilterForm, self).__init__(*args, **kwargs)

    monitoring_words_to_show = Nlpmonitorword.objects.filter(monitoringwords__name = self.request.GET.get('project')) 
    words_list = []
    for word in monitoring_words_to_show:
        words_list.append((word.monitor_word, word.monitor_word))    
    words_list = tuple(words_list)   # trying to get here tuple to pass in choises (('vk', 'vk'), ('fb', 'fb'), ('vkfb', 'vkfb'))

    project = forms.CharField(required=True, label='')
    monitor = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=words_list, required=False, label='')

2 个答案:

答案 0 :(得分:1)

您的表单需要的不是请求它是项目。最好在视图中处理请求并将所需参数传递给表单:

形式:

class PostfilterForm(forms.Form):
    def __init__(self, project, *args, **kwargs):
        self.project = project

查看:

project = request.GET.get('project')
form = PostfilterForm(project, request.POST)

答案 1 :(得分:1)

您尝试使用的所有代码都未在方法中使用,这意味着它不属于PostFilterForm的任何实例,因此不了解self更不用说字段。

你应该将这些包括在一个函数中,尽管应该是什么函数不清楚。

def my_function(self):
    monitoring_words_to_show = Nlpmonitorword.objects.filter(monitoringwords__name = self.request.GET.get('project')) 
    words_list = []
    for word in monitoring_words_to_show:
        words_list.append((word.monitor_word, word.monitor_word))    
    words_list = tuple(words_list)   # trying to get here tuple to pass in choises (('vk', 'vk'), ('fb', 'fb'), ('vkfb', 'vkfb'))