开发者

Accessing two returned values in Django view

开发者 https://www.devze.com 2023-02-28 18:05 出处:网络
I have my form clean method return two values. How do I distinguish the two variables in my view. Basically, I want to use the form data to check the database and return an object if it exists so that

I have my form clean method return two values. How do I distinguish the two variables in my view. Basically, I want to use the form data to check the database and return an object if it exists so that I can pass it to a new view. My goal is to not hit the database twice, once to see if the object exists and another time to retrieve it to display to the user.

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))


Will clean_field even work like that?

http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute

Note the comment.

You can put the attr on the form with 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 is on the form.

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))
0

精彩评论

暂无评论...
验证码 换一张
取 消