Monday, July 30, 2012

Handling Forms in Django, Twice-and-for-all (more form lifecycle, where and when can you still change stuff)



        if request.method == 'POST':
            self.product_edit_form = ProductEditForm(self.get_submit_data(), instance=self.product)
            self.create_product_edit_form()


            if not data.get('hidden_lang_change'): # A 'REAL' submit
                ##print "asdf", self.product_edit_form.cleaned_data ## FAILS: .cleaned_data attr, does not exist before call to is_valid()

                if self.product_edit_form.is_valid():
                    print "asdf", self.product_edit_form.cleaned_data
                #TEST: A 'language change submit': repopulate some fields from the Property table AFTER creating the form
                    self.product_edit_form.fields['description'].help_text = "AFAVSVAAAS"
                else:
                    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
                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.create_product_edit_form()
            print "new form"
##################################





Scenario:
So, you could change the HELP TEXT before the response rendering is returned,
but can you CHANGE THE VALUES INSIDE the <input> boxes? -- answer is, YES.







2 comments:

  1. SOLUTION: The last word:

    Recreate another instance of the form on submit, giving as args
    ({dict of form.cleaned_data with some of the keys changed,}, instance=self.product i.e. the product that the url is giving the id of)

    AND

    return the same View as the form's one (product_edit).
    That is, DON'T return redirect(...) .

    ReplyDelete
  2. Check out the next blog post for code snippet.

    Populating the form: Passing in a dict of form.fieldname:form.field.value,
    which could just be the form.cleaned_data (after calling form.is_valid()) from the immediately previous form submit.

    ReplyDelete