我的表单clean
方法返回两个值。如何在我的视图中区分这两个变量。基本上,我想使用表单数据来检查数据库并返回一个对象(如果它存在),以便我可以将它传递给新视图。我的目标是不要两次点击数据库,一次查看对象是否存在,另一次检索它以显示给用户。
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))
答案 0 :(得分:1)
clean_field会不会像那样工作?
http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute
注意评论。
您可以使用self
将表单放在表单上。
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('-')
self.q = None
try:
self.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
在表单上。
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 = code_lookup_form.q) # <---
return render_to_response('base/splash_page.html' ,{
'code_lookup_form' : code_lookup_form
}, context_instance=RequestContext(request))