Monday, July 30, 2012

Cleaned-up Form Submit/Repopulate program flow code snippet.

Same as previous post, but this is a clean skeleton, the comment clutter and line breaks cleaned up.



        self.build_breadcrumbs() #TODO: SLOTTED IN THIS HERE.
        #----------------------------------------------------

        if request.method == 'POST':
            # Define the form structure first. (population args=the POST data, db instance.)
            # Design in any custom (non-model) fields and their choices.
            self.product_edit_form = ProductEditForm(self.get_submit_data(), instance=self.product)
            self.customize_product_edit_form(self.product_edit_form)

            if not data.get('hidden_lang_change'): # If is a 'REAL' submit,
                if self.product_edit_form.is_valid():
                    # Repopulate the form: Modify .cleaned_data[key] and pass back in to form constructor.
                    self.product_edit_form.cleaned_data['description'] = "NEW DESC query from Property Table"
                    self.product_edit_form = ProductEditForm(self.product_edit_form.cleaned_data, instance=self.product)
                    print "lalalalaa"
                else:
                    # Handle form validation error,
                    # either self.error('msg')
                    # and/or return redirect(...)
                    self.product_edit_form.fields['description'].help_text = "zzzzzzzzzZZZZZZ"
                    print "efgh"
            else: # A 'language change submit': repopulate some fields from the Property table AFTER creating the form
                print "wxyz"
                pass
            print "submitted"
            # if errors, you end up at the same form here again. With "this field is required" error.
            # if no errors, you also end up submitted here UNLESS you "return redirect ..." -- but with no error messages on the form!
        else:
            self.product_edit_form = ProductEditForm(instance=self.product)
            self.customize_product_edit_form(self.product_edit_form)
            print "new form"




No comments:

Post a Comment