我有我的表格clean
方法返回兩個值。我如何區分我認爲的兩個變量。基本上,我想使用表單數據來檢查數據庫,並返回一個對象,如果它存在,以便我可以將它傳遞給新的視圖。我的目標是不打兩次數據庫,一次查看對象是否存在,另一次是檢索它以顯示給用戶。在Django視圖中訪問兩個返回值
Forms.py
class DocumentCodeLookup(forms.Form):
code = forms.CharField(max_length=15, error_messages={'required': 'Whoops! Please enter the Document Code from your ticket.'})
def clean_code(self):
code = self.cleaned_data['code'].upper()
if (re.match(r'^[A-Z0-9]{4,8}[-][A-Z0-9]{6}$',code)):
code_parts = code.split('-')
try:
q = Code.objects.get(user_defined_code__name=code_parts[0], document_code=code_parts[1])
except Code.DoesNotExist:
raise forms.ValidationError("Hmmm, we couldn't find that document.")
else:
raise forms.ValidationError("Hmmm, we couldn't find that document.")
return code, q
Views.py
def index(request):
code_lookup_form = DocumentCodeLookup()
if request.method == 'POST':
code_lookup_form = DocumentCodeLookup(request.POST)
if code_lookup_form.is_valid:
redirect('document', x = q) # I want to pass the returned object to the view
return render_to_response('base/splash_page.html' ,{
'code_lookup_form' : code_lookup_form
}, context_instance=RequestContext(request))
首先,Django使用緩存。兩次是沒有問題的。其次,你是否測量了這個?這是你的頭號瓶頸嗎? – 2011-04-22 20:31:07
我不確定我看到你在視圖的窗體中的clean_code()方法返回的'q'的值。看起來您需要將請求上下文傳遞給窗體,然後將q添加到上下文中,或者在窗體上爲q設置一個屬性,然後您可以在form.is_valid () – Brandon 2011-04-22 20:41:02