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











up vote
0
down vote

favorite












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
    2 days ago










  • 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
    2 days ago












  • 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
    2 days ago










  • 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
    yesterday

















up vote
0
down vote

favorite












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
    2 days ago










  • 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
    2 days ago












  • 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
    2 days ago










  • 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
    yesterday















up vote
0
down vote

favorite









up vote
0
down vote

favorite











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 18 hours ago

























asked 2 days ago









Anubis The Coding Nooby Puppy

32




32












  • What does parse_log do? What should the sample JSON look like?
    – Steve Piercy
    2 days ago










  • 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
    2 days ago












  • 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
    2 days ago










  • 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
    yesterday




















  • What does parse_log do? What should the sample JSON look like?
    – Steve Piercy
    2 days ago










  • 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
    2 days ago












  • 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
    2 days ago










  • 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
    yesterday


















What does parse_log do? What should the sample JSON look like?
– Steve Piercy
2 days ago




What does parse_log do? What should the sample JSON look like?
– Steve Piercy
2 days ago












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
2 days ago






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
2 days ago














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
2 days ago




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
2 days ago












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
yesterday






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
yesterday














1 Answer
1






active

oldest

votes

















up vote
0
down vote













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',
    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








    up vote
    0
    down vote













    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

























      up vote
      0
      down vote













      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























        up vote
        0
        down vote










        up vote
        0
        down vote









        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 2 days ago









        Steve Piercy

        6,07911535




        6,07911535






























             

            draft saved


            draft discarded



















































             


            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

            Wiesbaden

            Marschland

            Dieringhausen