Populating WTForm FormField in a Flask view when object doesn't match form field names











up vote
0
down vote

favorite












I have a form setup like so:



class AddressForm(FlaskForm):
line1 = StringField()
city = StringField()
postcode = StringField()

class PlaceForm(FlaskForm):
name = StringField()
address = FormField(AddressForm)


And then I have a Flask view something like this:



@bp.route("/places/<ident>", methods=['GET', 'POST'])
def edit_place(ident):
place = api.get_place(ident)

form = PlaceForm(obj=place)
if form.validate_on_submit():
# do stuff with the form data

return render_template('place/edit.html', form=form)


The api.get_place(ident) returns data that doesn't match the shape of the field names in my Form classes, so my forms are always empty when rendered in the browser. For example, the response from the API might look like this:



{
"place": {
"place_name": "Foobar",
"address": {
"address1": "500 5th St",
"locality": "San Francisco",
"post_code": "90210"
}
}
}


How do I customize the code populates the PlaceForm with data when passing in obj?










share|improve this question


























    up vote
    0
    down vote

    favorite












    I have a form setup like so:



    class AddressForm(FlaskForm):
    line1 = StringField()
    city = StringField()
    postcode = StringField()

    class PlaceForm(FlaskForm):
    name = StringField()
    address = FormField(AddressForm)


    And then I have a Flask view something like this:



    @bp.route("/places/<ident>", methods=['GET', 'POST'])
    def edit_place(ident):
    place = api.get_place(ident)

    form = PlaceForm(obj=place)
    if form.validate_on_submit():
    # do stuff with the form data

    return render_template('place/edit.html', form=form)


    The api.get_place(ident) returns data that doesn't match the shape of the field names in my Form classes, so my forms are always empty when rendered in the browser. For example, the response from the API might look like this:



    {
    "place": {
    "place_name": "Foobar",
    "address": {
    "address1": "500 5th St",
    "locality": "San Francisco",
    "post_code": "90210"
    }
    }
    }


    How do I customize the code populates the PlaceForm with data when passing in obj?










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have a form setup like so:



      class AddressForm(FlaskForm):
      line1 = StringField()
      city = StringField()
      postcode = StringField()

      class PlaceForm(FlaskForm):
      name = StringField()
      address = FormField(AddressForm)


      And then I have a Flask view something like this:



      @bp.route("/places/<ident>", methods=['GET', 'POST'])
      def edit_place(ident):
      place = api.get_place(ident)

      form = PlaceForm(obj=place)
      if form.validate_on_submit():
      # do stuff with the form data

      return render_template('place/edit.html', form=form)


      The api.get_place(ident) returns data that doesn't match the shape of the field names in my Form classes, so my forms are always empty when rendered in the browser. For example, the response from the API might look like this:



      {
      "place": {
      "place_name": "Foobar",
      "address": {
      "address1": "500 5th St",
      "locality": "San Francisco",
      "post_code": "90210"
      }
      }
      }


      How do I customize the code populates the PlaceForm with data when passing in obj?










      share|improve this question













      I have a form setup like so:



      class AddressForm(FlaskForm):
      line1 = StringField()
      city = StringField()
      postcode = StringField()

      class PlaceForm(FlaskForm):
      name = StringField()
      address = FormField(AddressForm)


      And then I have a Flask view something like this:



      @bp.route("/places/<ident>", methods=['GET', 'POST'])
      def edit_place(ident):
      place = api.get_place(ident)

      form = PlaceForm(obj=place)
      if form.validate_on_submit():
      # do stuff with the form data

      return render_template('place/edit.html', form=form)


      The api.get_place(ident) returns data that doesn't match the shape of the field names in my Form classes, so my forms are always empty when rendered in the browser. For example, the response from the API might look like this:



      {
      "place": {
      "place_name": "Foobar",
      "address": {
      "address1": "500 5th St",
      "locality": "San Francisco",
      "post_code": "90210"
      }
      }
      }


      How do I customize the code populates the PlaceForm with data when passing in obj?







      python flask flask-wtforms wtforms






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 at 0:31









      magneticMonster

      1,01142042




      1,01142042
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          I can't quite tell if this is actually the pattern you want. Since edit_place has both GET and POST methods do you really want to populate the form in both cases from the api.get_place() function, possibly overwriting the data from the request?



          Anyway you might try something like the following:



          class PlaceForm(FlaskForm):
          name = StringField()
          address = FormField(AddressForm)
          def __init__(self, *kwargs):
          super().__init__()
          self.address, self.name = # some code to populate with data from kwargs





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384566%2fpopulating-wtform-formfield-in-a-flask-view-when-object-doesnt-match-form-field%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            I can't quite tell if this is actually the pattern you want. Since edit_place has both GET and POST methods do you really want to populate the form in both cases from the api.get_place() function, possibly overwriting the data from the request?



            Anyway you might try something like the following:



            class PlaceForm(FlaskForm):
            name = StringField()
            address = FormField(AddressForm)
            def __init__(self, *kwargs):
            super().__init__()
            self.address, self.name = # some code to populate with data from kwargs





            share|improve this answer

























              up vote
              0
              down vote













              I can't quite tell if this is actually the pattern you want. Since edit_place has both GET and POST methods do you really want to populate the form in both cases from the api.get_place() function, possibly overwriting the data from the request?



              Anyway you might try something like the following:



              class PlaceForm(FlaskForm):
              name = StringField()
              address = FormField(AddressForm)
              def __init__(self, *kwargs):
              super().__init__()
              self.address, self.name = # some code to populate with data from kwargs





              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                I can't quite tell if this is actually the pattern you want. Since edit_place has both GET and POST methods do you really want to populate the form in both cases from the api.get_place() function, possibly overwriting the data from the request?



                Anyway you might try something like the following:



                class PlaceForm(FlaskForm):
                name = StringField()
                address = FormField(AddressForm)
                def __init__(self, *kwargs):
                super().__init__()
                self.address, self.name = # some code to populate with data from kwargs





                share|improve this answer












                I can't quite tell if this is actually the pattern you want. Since edit_place has both GET and POST methods do you really want to populate the form in both cases from the api.get_place() function, possibly overwriting the data from the request?



                Anyway you might try something like the following:



                class PlaceForm(FlaskForm):
                name = StringField()
                address = FormField(AddressForm)
                def __init__(self, *kwargs):
                super().__init__()
                self.address, self.name = # some code to populate with data from kwargs






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 20 at 21:36









                Attack68

                9291411




                9291411






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384566%2fpopulating-wtform-formfield-in-a-flask-view-when-object-doesnt-match-form-field%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Feedback on college project

                    Futebolista

                    Albești (Vaslui)