Python 为什么request.user在自定义清理表单中出现错误?
为什么此db查询中的request.user获得全局名称“request”未定义错误? 在try定义的外部和内部? 此代码位于自定义的干净定义中:Python 为什么request.user在自定义清理表单中出现错误?,python,django,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']
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
当您引用
请求时(请注意,它不是一个参数,希望不是全局的),它在名称空间中不存在。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
也许不重要,但你的第二次尝试对我来说没有多大意义