Feeding JSON into Dynatable after user submission via Deform (Pyramid)












1















I'm building a webpage which takes user input and returns a table based on information in my backend. I'm using the web framework Pyramid. My current approach is the following:




  1. Create a Colander Schema and a Deform form object that is rendered using a Chameleon template.


  2. Once the user hits submit, validate the submission and use the input to generate a list of dictionaries.


  3. Encode this result into JSON and feed it to dynatable.js


  4. Display the dynatable below my submission form



Steps 3 and 4 are where I'm having an issue. I don't know what I need to do to expose my list of dictionaries to dynatable. I've read the Pyramid Quick Tutorial, so I have an idea of how to do simple AJAX with a JSON renderer, but I have no idea how to implement this into my current situation.



To give a better idea, my function for processing Deform input is as follows (part of the function and template is adapted from the Deform sample provided on the official Github repo):



@view_config(route_name='query_log', renderer='templates/form.pt') 
def query_log(request):

schema = Device().bind(request=request)

# Create a styled button with some extra Bootstrap 3 CSS classes
process_btn = deform.form.Button(name='process', title="Process")
form = deform.form.Form(schema, buttons=(process_btn,), use_ajax=True)

# User submitted this form
if request.method == "POST":
if 'process' in request.POST:

try:
appstruct = form.validate(request.POST.items())

# Save form data from appstruct
print("Enter ID:", appstruct["ID"])
print("Enter date:", appstruct["date"])

# This variable is what I want to feed to dynatable
results = parse_log(appstruct["ID"], appstruct["date"].strftime('%Y-%m-%d'))
json.dumps(results)

# Create ppoup
request.session.flash('Returning Results.')

# Redirect to the page shows after succesful form submission
return HTTPFound("/")

except deform.exception.ValidationFailure as e:
# Render a form version where errors are visible next to the fields,
# and the submitted values are posted back
rendered_form = e.render()
else:
# Render a form with initial default values
rendered_form = form.render()

return {
# This is just rendered HTML in a string
# and can be embedded in any template language
"rendered_form": rendered_form,
}


How would I go about passing this results variable via JSON to Dynatable and have the table rendered below the form?










share|improve this question

























  • What does parse_log do? What should the sample JSON look like?

    – Steve Piercy
    Nov 19 '18 at 12:43











  • parse_log just takes in the user input (id and date) and generates a list of dictionaries by parsing a log file. A sample result with two dictionaries would look like this: [{"date": "2018-11-18", "time": "00:00:08", "id": "B5:22:EA:40:00:6B", "val": "989", "area": "base1"}, {"date": "2018-11-18", "time": "00:20:48", "id": "2F:61:C1:9C:84:FA", "val": "9", "area": "base4"}]. This what I want to feed to dynatable.js (dynatable.com).

    – Anubis The Coding Nooby Puppy
    Nov 19 '18 at 19:58













  • I think my answer below will get you started. You can modify it to include other fields. I would recommend, however, that you use persistent storage (a database) to save the submitted records first, then separately perform a query. There are examples in the Pyramid docs for that.

    – Steve Piercy
    Nov 19 '18 at 23:16











  • The only reason I haven't opted to use persistent storage yet is because my user input just seems too trivial to require it. The only thing I need input for is to generate a query to load a table.

    – Anubis The Coding Nooby Puppy
    Nov 20 '18 at 20:44


















1















I'm building a webpage which takes user input and returns a table based on information in my backend. I'm using the web framework Pyramid. My current approach is the following:




  1. Create a Colander Schema and a Deform form object that is rendered using a Chameleon template.


  2. Once the user hits submit, validate the submission and use the input to generate a list of dictionaries.


  3. Encode this result into JSON and feed it to dynatable.js


  4. Display the dynatable below my submission form



Steps 3 and 4 are where I'm having an issue. I don't know what I need to do to expose my list of dictionaries to dynatable. I've read the Pyramid Quick Tutorial, so I have an idea of how to do simple AJAX with a JSON renderer, but I have no idea how to implement this into my current situation.



To give a better idea, my function for processing Deform input is as follows (part of the function and template is adapted from the Deform sample provided on the official Github repo):



@view_config(route_name='query_log', renderer='templates/form.pt') 
def query_log(request):

schema = Device().bind(request=request)

# Create a styled button with some extra Bootstrap 3 CSS classes
process_btn = deform.form.Button(name='process', title="Process")
form = deform.form.Form(schema, buttons=(process_btn,), use_ajax=True)

# User submitted this form
if request.method == "POST":
if 'process' in request.POST:

try:
appstruct = form.validate(request.POST.items())

# Save form data from appstruct
print("Enter ID:", appstruct["ID"])
print("Enter date:", appstruct["date"])

# This variable is what I want to feed to dynatable
results = parse_log(appstruct["ID"], appstruct["date"].strftime('%Y-%m-%d'))
json.dumps(results)

# Create ppoup
request.session.flash('Returning Results.')

# Redirect to the page shows after succesful form submission
return HTTPFound("/")

except deform.exception.ValidationFailure as e:
# Render a form version where errors are visible next to the fields,
# and the submitted values are posted back
rendered_form = e.render()
else:
# Render a form with initial default values
rendered_form = form.render()

return {
# This is just rendered HTML in a string
# and can be embedded in any template language
"rendered_form": rendered_form,
}


How would I go about passing this results variable via JSON to Dynatable and have the table rendered below the form?










share|improve this question

























  • What does parse_log do? What should the sample JSON look like?

    – Steve Piercy
    Nov 19 '18 at 12:43











  • parse_log just takes in the user input (id and date) and generates a list of dictionaries by parsing a log file. A sample result with two dictionaries would look like this: [{"date": "2018-11-18", "time": "00:00:08", "id": "B5:22:EA:40:00:6B", "val": "989", "area": "base1"}, {"date": "2018-11-18", "time": "00:20:48", "id": "2F:61:C1:9C:84:FA", "val": "9", "area": "base4"}]. This what I want to feed to dynatable.js (dynatable.com).

    – Anubis The Coding Nooby Puppy
    Nov 19 '18 at 19:58













  • I think my answer below will get you started. You can modify it to include other fields. I would recommend, however, that you use persistent storage (a database) to save the submitted records first, then separately perform a query. There are examples in the Pyramid docs for that.

    – Steve Piercy
    Nov 19 '18 at 23:16











  • The only reason I haven't opted to use persistent storage yet is because my user input just seems too trivial to require it. The only thing I need input for is to generate a query to load a table.

    – Anubis The Coding Nooby Puppy
    Nov 20 '18 at 20:44
















1












1








1








I'm building a webpage which takes user input and returns a table based on information in my backend. I'm using the web framework Pyramid. My current approach is the following:




  1. Create a Colander Schema and a Deform form object that is rendered using a Chameleon template.


  2. Once the user hits submit, validate the submission and use the input to generate a list of dictionaries.


  3. Encode this result into JSON and feed it to dynatable.js


  4. Display the dynatable below my submission form



Steps 3 and 4 are where I'm having an issue. I don't know what I need to do to expose my list of dictionaries to dynatable. I've read the Pyramid Quick Tutorial, so I have an idea of how to do simple AJAX with a JSON renderer, but I have no idea how to implement this into my current situation.



To give a better idea, my function for processing Deform input is as follows (part of the function and template is adapted from the Deform sample provided on the official Github repo):



@view_config(route_name='query_log', renderer='templates/form.pt') 
def query_log(request):

schema = Device().bind(request=request)

# Create a styled button with some extra Bootstrap 3 CSS classes
process_btn = deform.form.Button(name='process', title="Process")
form = deform.form.Form(schema, buttons=(process_btn,), use_ajax=True)

# User submitted this form
if request.method == "POST":
if 'process' in request.POST:

try:
appstruct = form.validate(request.POST.items())

# Save form data from appstruct
print("Enter ID:", appstruct["ID"])
print("Enter date:", appstruct["date"])

# This variable is what I want to feed to dynatable
results = parse_log(appstruct["ID"], appstruct["date"].strftime('%Y-%m-%d'))
json.dumps(results)

# Create ppoup
request.session.flash('Returning Results.')

# Redirect to the page shows after succesful form submission
return HTTPFound("/")

except deform.exception.ValidationFailure as e:
# Render a form version where errors are visible next to the fields,
# and the submitted values are posted back
rendered_form = e.render()
else:
# Render a form with initial default values
rendered_form = form.render()

return {
# This is just rendered HTML in a string
# and can be embedded in any template language
"rendered_form": rendered_form,
}


How would I go about passing this results variable via JSON to Dynatable and have the table rendered below the form?










share|improve this question
















I'm building a webpage which takes user input and returns a table based on information in my backend. I'm using the web framework Pyramid. My current approach is the following:




  1. Create a Colander Schema and a Deform form object that is rendered using a Chameleon template.


  2. Once the user hits submit, validate the submission and use the input to generate a list of dictionaries.


  3. Encode this result into JSON and feed it to dynatable.js


  4. Display the dynatable below my submission form



Steps 3 and 4 are where I'm having an issue. I don't know what I need to do to expose my list of dictionaries to dynatable. I've read the Pyramid Quick Tutorial, so I have an idea of how to do simple AJAX with a JSON renderer, but I have no idea how to implement this into my current situation.



To give a better idea, my function for processing Deform input is as follows (part of the function and template is adapted from the Deform sample provided on the official Github repo):



@view_config(route_name='query_log', renderer='templates/form.pt') 
def query_log(request):

schema = Device().bind(request=request)

# Create a styled button with some extra Bootstrap 3 CSS classes
process_btn = deform.form.Button(name='process', title="Process")
form = deform.form.Form(schema, buttons=(process_btn,), use_ajax=True)

# User submitted this form
if request.method == "POST":
if 'process' in request.POST:

try:
appstruct = form.validate(request.POST.items())

# Save form data from appstruct
print("Enter ID:", appstruct["ID"])
print("Enter date:", appstruct["date"])

# This variable is what I want to feed to dynatable
results = parse_log(appstruct["ID"], appstruct["date"].strftime('%Y-%m-%d'))
json.dumps(results)

# Create ppoup
request.session.flash('Returning Results.')

# Redirect to the page shows after succesful form submission
return HTTPFound("/")

except deform.exception.ValidationFailure as e:
# Render a form version where errors are visible next to the fields,
# and the submitted values are posted back
rendered_form = e.render()
else:
# Render a form with initial default values
rendered_form = form.render()

return {
# This is just rendered HTML in a string
# and can be embedded in any template language
"rendered_form": rendered_form,
}


How would I go about passing this results variable via JSON to Dynatable and have the table rendered below the form?







json ajax pyramid dynatable deform






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 8:24







Anubis The Coding Nooby Puppy

















asked Nov 19 '18 at 10:37









Anubis The Coding Nooby PuppyAnubis The Coding Nooby Puppy

203




203













  • What does parse_log do? What should the sample JSON look like?

    – Steve Piercy
    Nov 19 '18 at 12:43











  • parse_log just takes in the user input (id and date) and generates a list of dictionaries by parsing a log file. A sample result with two dictionaries would look like this: [{"date": "2018-11-18", "time": "00:00:08", "id": "B5:22:EA:40:00:6B", "val": "989", "area": "base1"}, {"date": "2018-11-18", "time": "00:20:48", "id": "2F:61:C1:9C:84:FA", "val": "9", "area": "base4"}]. This what I want to feed to dynatable.js (dynatable.com).

    – Anubis The Coding Nooby Puppy
    Nov 19 '18 at 19:58













  • I think my answer below will get you started. You can modify it to include other fields. I would recommend, however, that you use persistent storage (a database) to save the submitted records first, then separately perform a query. There are examples in the Pyramid docs for that.

    – Steve Piercy
    Nov 19 '18 at 23:16











  • The only reason I haven't opted to use persistent storage yet is because my user input just seems too trivial to require it. The only thing I need input for is to generate a query to load a table.

    – Anubis The Coding Nooby Puppy
    Nov 20 '18 at 20:44





















  • What does parse_log do? What should the sample JSON look like?

    – Steve Piercy
    Nov 19 '18 at 12:43











  • parse_log just takes in the user input (id and date) and generates a list of dictionaries by parsing a log file. A sample result with two dictionaries would look like this: [{"date": "2018-11-18", "time": "00:00:08", "id": "B5:22:EA:40:00:6B", "val": "989", "area": "base1"}, {"date": "2018-11-18", "time": "00:20:48", "id": "2F:61:C1:9C:84:FA", "val": "9", "area": "base4"}]. This what I want to feed to dynatable.js (dynatable.com).

    – Anubis The Coding Nooby Puppy
    Nov 19 '18 at 19:58













  • I think my answer below will get you started. You can modify it to include other fields. I would recommend, however, that you use persistent storage (a database) to save the submitted records first, then separately perform a query. There are examples in the Pyramid docs for that.

    – Steve Piercy
    Nov 19 '18 at 23:16











  • The only reason I haven't opted to use persistent storage yet is because my user input just seems too trivial to require it. The only thing I need input for is to generate a query to load a table.

    – Anubis The Coding Nooby Puppy
    Nov 20 '18 at 20:44



















What does parse_log do? What should the sample JSON look like?

– Steve Piercy
Nov 19 '18 at 12:43





What does parse_log do? What should the sample JSON look like?

– Steve Piercy
Nov 19 '18 at 12:43













parse_log just takes in the user input (id and date) and generates a list of dictionaries by parsing a log file. A sample result with two dictionaries would look like this: [{"date": "2018-11-18", "time": "00:00:08", "id": "B5:22:EA:40:00:6B", "val": "989", "area": "base1"}, {"date": "2018-11-18", "time": "00:20:48", "id": "2F:61:C1:9C:84:FA", "val": "9", "area": "base4"}]. This what I want to feed to dynatable.js (dynatable.com).

– Anubis The Coding Nooby Puppy
Nov 19 '18 at 19:58







parse_log just takes in the user input (id and date) and generates a list of dictionaries by parsing a log file. A sample result with two dictionaries would look like this: [{"date": "2018-11-18", "time": "00:00:08", "id": "B5:22:EA:40:00:6B", "val": "989", "area": "base1"}, {"date": "2018-11-18", "time": "00:20:48", "id": "2F:61:C1:9C:84:FA", "val": "9", "area": "base4"}]. This what I want to feed to dynatable.js (dynatable.com).

– Anubis The Coding Nooby Puppy
Nov 19 '18 at 19:58















I think my answer below will get you started. You can modify it to include other fields. I would recommend, however, that you use persistent storage (a database) to save the submitted records first, then separately perform a query. There are examples in the Pyramid docs for that.

– Steve Piercy
Nov 19 '18 at 23:16





I think my answer below will get you started. You can modify it to include other fields. I would recommend, however, that you use persistent storage (a database) to save the submitted records first, then separately perform a query. There are examples in the Pyramid docs for that.

– Steve Piercy
Nov 19 '18 at 23:16













The only reason I haven't opted to use persistent storage yet is because my user input just seems too trivial to require it. The only thing I need input for is to generate a query to load a table.

– Anubis The Coding Nooby Puppy
Nov 20 '18 at 20:44







The only reason I haven't opted to use persistent storage yet is because my user input just seems too trivial to require it. The only thing I need input for is to generate a query to load a table.

– Anubis The Coding Nooby Puppy
Nov 20 '18 at 20:44














1 Answer
1






active

oldest

votes


















1














Try baby steps first.



After validation is successful in your try block:



try:
appstruct = form.validate(request.POST.items())
# following depends on structure of data you need
results = dict("id" = appstruct["ID"],
"date" = appstruct["date"].strftime('%Y-%m-%d'))
data = json.dumps(results)
return dict(data=data)


And in the target template, accept the data parameter, rendering to taste.



Once you have that in place, then you can work on how to pass data via an XHR request, which will depend on your choice of JavaScript library.






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',
    autoActivateHeartbeat: false,
    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%2f53372792%2ffeeding-json-into-dynatable-after-user-submission-via-deform-pyramid%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









    1














    Try baby steps first.



    After validation is successful in your try block:



    try:
    appstruct = form.validate(request.POST.items())
    # following depends on structure of data you need
    results = dict("id" = appstruct["ID"],
    "date" = appstruct["date"].strftime('%Y-%m-%d'))
    data = json.dumps(results)
    return dict(data=data)


    And in the target template, accept the data parameter, rendering to taste.



    Once you have that in place, then you can work on how to pass data via an XHR request, which will depend on your choice of JavaScript library.






    share|improve this answer




























      1














      Try baby steps first.



      After validation is successful in your try block:



      try:
      appstruct = form.validate(request.POST.items())
      # following depends on structure of data you need
      results = dict("id" = appstruct["ID"],
      "date" = appstruct["date"].strftime('%Y-%m-%d'))
      data = json.dumps(results)
      return dict(data=data)


      And in the target template, accept the data parameter, rendering to taste.



      Once you have that in place, then you can work on how to pass data via an XHR request, which will depend on your choice of JavaScript library.






      share|improve this answer


























        1












        1








        1







        Try baby steps first.



        After validation is successful in your try block:



        try:
        appstruct = form.validate(request.POST.items())
        # following depends on structure of data you need
        results = dict("id" = appstruct["ID"],
        "date" = appstruct["date"].strftime('%Y-%m-%d'))
        data = json.dumps(results)
        return dict(data=data)


        And in the target template, accept the data parameter, rendering to taste.



        Once you have that in place, then you can work on how to pass data via an XHR request, which will depend on your choice of JavaScript library.






        share|improve this answer













        Try baby steps first.



        After validation is successful in your try block:



        try:
        appstruct = form.validate(request.POST.items())
        # following depends on structure of data you need
        results = dict("id" = appstruct["ID"],
        "date" = appstruct["date"].strftime('%Y-%m-%d'))
        data = json.dumps(results)
        return dict(data=data)


        And in the target template, accept the data parameter, rendering to taste.



        Once you have that in place, then you can work on how to pass data via an XHR request, which will depend on your choice of JavaScript library.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 '18 at 12:54









        Steve PiercySteve Piercy

        6,31611536




        6,31611536






























            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.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372792%2ffeeding-json-into-dynatable-after-user-submission-via-deform-pyramid%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

            Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

            ComboBox Display Member on multiple fields

            Is it possible to collect Nectar points via Trainline?