How to generate a dynamic search form for Django? - javascript

I wrote a REST API based on Django's ORM. Here's some examples of my REST API
curl "http://example.com/api/pcserver?last_update__lt=2012-06-01 00:00:00&hostname__startswith=xen"
On server side, I uses a queryset.filter() function to process all the GET parameters, and convert the result queryset into a json, then return to user.
Now I'm having trouble convert this API into web based search form.
What I want to have about this magic search form:
dynamic add/delete query parameters using javascript, join them using AND (I don't need OR between these parameters)
provide drop down menu to select the field to be searched based on the model
support for selecting operators e.g. __lt, __gt, __regex
Are there any wheels out there so I don't have to re-invent it? Thank you:-)

#yegle
I'd suggest to use this media type: http://code.ge/media-types/collection-next-json/ it's an extension of the: http://amundsen.com/media-types/collection/format/ media type and you can achieve your goal without problems.
Look at this document:
{"collection": {
"version": 1.0,
"queries": [
{
"href": "http://service.com/my-resource",
"rel": "search",
"prompt": "Enter search string",
"data" : [
{
"name": "query",
"prompt": "Search query",
"required": true
}, {
"name": "gender",
"prompt": "Gender",
"list": {
"default": "female",
"options": [
{"value": "female", "prompt": "Female"},
{"value": "male", "prompt": "Male"}
]
}
}
]
}
]
}}
with "queries" array you can describe several search templates which easily can be transformed to the HTML form. In each query object you can define:
Search URI
Title of the "form"(i.e. prompt); and
Any number of query parameters with different requirements.
As you see from example above there are two query parameters - "query" and "gender", of which "query" parameter can be converted to HTML.input and "gender" parameter to HTML.select.
I hope I correctly understood your question and goal.

I am not sure about django tools.However,you can use MYSQL's full text boolean search to achieve most of the above requirements.Refer the below link and revert back with your comments!
http://dev.mysql.com/doc/refman//5.5/en/fulltext-boolean.html

Have a look at django-filter
Or, in some hacking way, use Django Admin. You could customize a ModelAdmin for the target model and use ChangeList to deal w/ querystring. Take built-in User for example:
from django.contrib.admin.options.IncorrectLookupParameters
from django.contrib.admin.views.main import ChangeList
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
self = UserAdmin(User, None) # or taken from admin.site._registry if the model admin is registered
cl = ChangeList(request, User, self.list_display,
self.list_display_links, self.list_filter, self.date_hierarchy,
self.search_fields, self.list_select_related,
self.list_per_page, self.list_max_show_all, self.list_editable,
self)
# then cl.get_query_set would process querystring and generate the queryset
try:
cl.get_query_set(request)
except IncorrectLookupParameters:
'encounter an invalid lookup'

Related

For Prisma Client join queries is it possible to move deeply nested fields to top level of result?

Does Prisma have the ability to move nested fields from another table join to the top level of the result, like a flattened view? I want to put the result JSON into a frontend table without digging through nested objects and building another object.
For example I want to replicate this behavior where I can pick and choose the columns from different tables (columns from User, and School). Currently I use a raw query with a similar SQL, however I wonder if it's possible with using only the Prisma API:
SELECT
u.id
, u.email
, s.school_name
FROM "User" AS u
JOIN "UserSchool" AS us ON us.user_id = u.id
JOIN "School" AS s ON s.id = us.school_id
id | email | school_name
123| student1#email.com | mount high
I want JSON that looks like this:
{
"id": "1",
"email": "student1#email.com",
"school_name": "mount high",
}
If I did this in Prisma, I would need to go into several levels of nested objects to get the same column name on another table for e.g. user[user_school][schoo][school_name]. This requires extra work to loop through all my results, extract from the nested object, and build another object. This example isn't too bad, but I have more joins and deeply nested objects for my actual problem (lots of association/lookup tables). I've experimented with the select and include for my joins, but they are structured with the nested JSON.
users = await prisma.user.findMany({
include: {
user_school: {
include: {
school: true,
},
},
},
{
"id": "1",
"email": "student1#email.com",
"user_school": [
{
"id": 1,
"user_id": "1",
"school_id": "1",
"school": {
"id": 1,
"school_name": "mountain high",
}
}
],
}
It's not possible to flatten out the results as of now.
The only way to achieve this would be by using rawQuery as you mentioned.
However, there is an existing Feature Request which discusses Flattening out the results by providing an option of flatten:true. If you could mention your use case there and add a comment it would help Prisma's Product and engineering team in prioritising it.

Adding and removing items from a cart in Dialogflow

I am prototyping a Food Ordering app using Dialogflow(Chatbot maker) and got stuck with this problem. Technically, I want to persist the gathered data from an Intent after the user decided to "add more items to their order" and satisfies all the required parameters, which are, (itemName, quantity, [variants], [sauceType], ...).
The chat bot should be able to handle a request which consist of multiple items with their corresponding quantities but I am not sure if it's possible to model a data wherein it consist an array of Entities so, my first thought was to use a persistent Fulfillment using session-based Webhook with our custom Web Service, like for example: foodorder/api/order/123/items/add and 123 being the Session Id. But this approach requires more work and the generated model can be difficult to translate in Dialoflow Console.
The second solution comes into my mind, is to leverage the Intent property called Action and Parameters where we mark the Entity as List, but using this approach, the quantity doesn't get attached to the item itself.
My question is, how can I be able to model a data using Dialogflow that resembles something like below:
{
"givenName": "Dummy User",
"order": [
{
"itemName": "Burger",
"quantity": 2
},
{
"itemName": "6 piece Chicken Nuggets",
"quantity": 1,
"sauceType": "Tangy Barbeque"
},
{
"itemName": "Coke",
"quantity": 1,
"size": "Small"
}
]
}
Turns out what I was looking for was Composite Entities and mark it as a list.
The detailed answer can be found on this link:
https://stackoverflow.com/a/47166123/2304737

How can I generate dialogs dynamically using the Microsoft Bot Builder SDK for Node.js?

I am building a tool that allows users to generate their own custom form surveys. I would like to give them the ability to convert these traditional form surveys into a chat conversation. I am already using the Microsoft Bot Builder SDK to interact with users through chat.
How can I generate dialogs dynamically using the form structure that is stored in my database? Assume that I have an array like this one stored in my database:
var form = [
{
inputType: 'text',
prompt: 'What is your first name?'
},
{
inputType: 'choice',
prompt: 'Select your gender',
values: ['female', 'male']
}
];
How can I generate a waterfall dialog using this array? I know I can just manually write the dialog code using prompts etc. if I know what the survey questions are all the time but I have to generate the dialog based on a dynamic form that users save. I can't find any information about how to achieve this. Appreciate the help. Thanks.
You can accomplish this using a community contributed tool called "Form Flow" - it is designed to accomplish a similar idea to yours.
You can find the NPM package here:
https://www.npmjs.com/package/botbuilder-formflow
More details available on the GitHub project repository here:
https://github.com/gudwin/botbuilder-formflow
Overview:
This Library will allow your bot to request complex forms from a user. It helps to build a waterfall dialog that will handle the whole form flow. The library will split into a list of dialogs required for each field. You can use predefined prompts or create you custom dialog wrappers around MBF prompts. Dialogs for each field evaluated separately and could be customized. The Library features:
Standard Prompts plus prompts for emails and urls;
Validators, Prompts, Error Prompts and Value extractors could be customized by a developer
Subdialogs are supported
Example: Simple registration form:
const builder = require('botbuilder');
const formFlow = require('../../botbuilder-formflow');
let signupForm = [
{
"type": "text",
"id": "login",
"prompt": "Please enter your login",
"response": "Your login is %s"
},
{
"type": "text",
"id": "password",
"prompt": "Please enter your password",
"response": "Your password is %s"
}
];
let connector = new builder.ConsoleConnector().listen();
let bot = new builder.UniversalBot(connector);
bot.dialog('/', [
session => session.beginDialog('/form'),
(session, response) => session.endDialog(`Form result: ${JSON.stringify(response.response)}`)
]);
formFlow.create(bot, '/form', signupForm);
console.log('To start registration flow press [[ENTER]]');
Alternatively, besides leveraging the npm package as #nilsw mentioned, you can try to build up an Adaptive Card json string by yourself from the entities in your database.
The field definition code snippet is simple:
{
"type": "TextBlock",
"text": "Your name",
"wrap": true
},
{
"type": "Input.Text",
"id": "myName",
"placeholder": "Last, First"
},
You can refer http://adaptivecards.io/samples/InputForm.html for the input form sample.
And also, refer to http://adaptivecards.io/explorer/Input.Choice.html for the fields definitions.

How to POST json to the Wufoo Entries API?

The current documentation is a little lacking on how exactly to submit forms via Ajax. There is The Entries POST API but it talks only about xml, and doesn't even show an example payload.
I see that Wufoo has a half-built, abandoned jQuery plugin wufoo/Wufoo-jQuery-API-Wrapper which seems to do little more than wrap $.get and format errors a bit. POST is listed as a "todo".
I've tried hitting the API with things like:
{
"Field1": "first",
"Field2": "last",
"Field3": "email#example.com",
"Field4": "test messsage",
}
And based on the line "This call would contain POST parameters in name/value pairs" and the example postAuthenticated(array('Field1' => 'Frank')); I tried just sending an array of arrays.
[
['Field1', 'first'],
['Field2', 'last'],
['Field3', 'email#example.com'],
['Field4', 'test messsage']
]
But since those are obviously the wrong format, I always get the following in response.
{
"Success": 0,
"ErrorText": "Errors have been <b>highlighted</b> below.",
"FieldErrors": [
{
"ID": "Field3",
"ErrorText": "This field is required. Please enter a value."
},
{
"ID": "Field4",
"ErrorText": "This field is required. Please enter a value."
}
]
}
Does anyone have any idea how to format these requests? Maybe someone with more experience with CurlService could interpret it from their example, but I can't make heads or tails of that documentation, nor find any examples online.
I should have known. The service doesn't accept json, it only replies in json. Submitting a regular urlencoded form body works.

Using jQuery's serializeArray with Rails forms

I'm trying to display an order summary on the final screen of a checkout process (buit in Rails 3). Nothing is submitted prior to this, so I'm using jQuery's serializeArray() to get all the names and values from the form fields, which works great. I collect a variety of nested attributes, so the returned array is rather busy, with names like order[donations_attributes][0][amount_in_dollars].
Is there a straightforward way, in Javascript (or using jQuery) to convert those names and values to a JSON string (which would make it way easier to work with to produce my summary output). For example, something like:
{
"order": {
"donations_attributes": [
{
"amount_in_dollars": 50.95,
"category": "Some Fund"
},
{
"amount_in_dollars": 90.92,
"category": "Some Other Fund"
}
],
"billing_address_attributes": {
"first_name": "Bob",
"last_name": "Smith",
"address1": "123 Whatever Street",
"and so on": "etc"
}
}
}
Keep in mind that I haven't submitted anything yet (nor can I), so I can't do it in Ruby. Is there a sort of obvious, straightforward way to do this, or will I need to parse out and build the string by hand?
You can pass that data as-is to the data parameter in JQuery.ajax(...), and it will end up in parama in the controller method and view for the action you call, .e.g params[:order][:donations_attributes][0][:category] == "Some Fund".
If you want to load a new url into the browser, you can use JQuery.serialize() on the data and append it to your url (with a `"?" in between) to create the URL with the appropriate query string.

Categories

Resources