[英]Why does request.user get errors in a custom clean form?
為什么在此數據庫查詢中的request.user獲取全局名稱'request'未定義錯誤? 嘗試定義的內部和外部? 這段代碼位於一個自定義的干凈定義內:
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
在您引用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
也許並不重要,但是您的第二個嘗試塊對我而言並沒有多大意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.