为什么request.user在自定义清理表单中出错?

时间:2015-01-10 02:56:02

标签: python django

为什么此db查询中的request.user获取全局名称'request'未定义错误? 在try定义的外侧和内侧? 此代码位于自定义清理定义中:

class QuestionForm(forms.Form):

    question= forms.CharField(label = ('question'))

    def clean_question(self):
        self.question = self.cleaned_data['question']
        self.question = self.question.lower()
        y = ''
        for c in self.question:
            if c != '?':
                y+=str(c)
        self.question = y
        try:
            QuestionModel.objects.get(question= self.question)
        except QuestionModel.DoesNotExist:
            x = QuestionModel(question= self.question)
            x.save()

        y = TheirAnswerModel.objects.get(user= request.user, question_id= x.id) #here

        try:
            x = QuestionModel.objects.get(question= self.question)
            y = TheirAnswerModel.objects.get(user= request.user, question_id= x.id) and here
            raise forms.ValidationError("You have already asked that question")
        except TheirAnswerModel.DoesNotExist:
            return self.question

1 个答案:

答案 0 :(得分:2)

您引用request的位置(注意它不是参数,希望不是全局参数),它在命名空间中不存在。 Django故意将表单与请求对象分开,因此您需要创建自己的init方法,将其作为参数。

class QuestionForm(forms.Form): 

    question = forms.CharField(label = ('question'))


    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(QuestionForm, self).__init__(*args, **kwargs)

    def clean_question(self):

        # this is the only line I modified (besides a little cleanup)
        request = self.request

        self.question = self.cleaned_data['question']
        self.question = self.question.lower()
        y = ''
        for c in self.question:
            if c != '?':
                y+=str(c)
        self.question = y
        try:
            QuestionModel.objects.get(question= self.question)
        except QuestionModel.DoesNotExist:
            x = QuestionModel(question= self.question)
            x.save()

        y = TheirAnswerModel.objects.get(user= request.user, question_id= x.id) #here

        try:
            x = QuestionModel.objects.get(question= self.question)
            y = TheirAnswerModel.objects.get(user= request.user, question_id= x.id) #and here
            raise forms.ValidationError("You have already asked that question")
        except TheirAnswerModel.DoesNotExist:
            return self.question

也许并不重要,但是你的第二次尝试对我来说并没有多大意义。