I'm using Hansontable to allow users to create a matrix of input variables. How do I pass this matrix back to my views.py without it being part of the input form? I can add a form field for a 2-dimensional array, but I don't actually need it since the hansontable is creating the "input field".
I need to compute a set of results using the matrix before echoing it back to the user along with the results and storing it in a bd.
Any guidance is greatly appreciated.
Thanks.
To do pass any data to a backend without using a HTML form (without refreshing the page) you have to utilize AJAX methodologies/practice. Using jQuery you can do this like so:
$.ajax({
method: "POST",
url: "/some/url",
data: JSON.stringify(<handsontabledom>.getData())
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Also note there is a tutorial on the Handson Tables documentation all about saving the data via a ajax request.
http://docs.handsontable.com/0.19.0/tutorial-load-and-save.html
Related
I use django-multiselectfield package in my project and based on its docs I use MultipleChoiceField in my serializer:
class InsCatSerializer(serializers.ModelSerializer):
levels = fields.MultipleChoiceField(choices=LEVEL)
when I send a request with raw JSON in postman that works fine
"levels": ["INTERMEDIATE", "ADVANCED"]
But I need to use form data because I have files and images in my request!
I try this way:
levels:INTERMEDIATE
levels:ADVANCED
but just saved the last element ( ADVANCED in this example )
any suggestion to solve?
Json Array and Form data can't work together. Please stringify your array or don't use form data at all.
Read more: JS, how to append array in FormData?
I need to write a view to delete multiple objects in one go.
I have modified the HTML template, put checkboxes to select which objects (users) to delete and a button to delete them, but of course you need a view to perform the task.
When you have one item to select at a time, you pass its primary key to the view through the url, how can I extend this to pass more than one primary key?
You would absolutely not be doing this via the URL. If you have a set of checkboxes, then you have a form; since the form is doing destructive operations it will be submitted via POST: therefore your set of IDs is in request.POST.
What you can do is to send the data in a JSON format, which can easily be decoded by Django
On the frontend, you'd have a JavaScript for a button like so,
function delete_object(pks) {
var args = {type: "POST", url: "/delete/", data: {'pks': pks}};
$.ajax(args);
return false;
}
this function would take selected the primary keys from (which is passed in as pks) and POST it to the Django url ^delete/$. A Django view function can then handle the incoming data like so,
def delete(request):
object_pks = request.POST['pks']
Docs.objects.filter(pk__in=object_pks).delete()
I'm trying to get autocomplete working in my rails application using Magic Suggest.
I think this is the correct question: How can I get MagicSuggest to grab the JSON that is at the URL I give it?
This is the error that console returns when I type letters:
POST http://localhost:3000/search_foods 404 (Not Found) jquery.js:8706
Uncaught Could not reach server
Here's the magic suggest code:
input.magicSuggest({
data: "/foods/search/",
placeholder: "Search Foods...",
valueField:'idFood',
displayField:'foodName'
});
The Routes
resources :search_foods
The Controller and Action
class SearchFoodsController < ApplicationController
def index
render json: %['Crack', 'Cocain', 'Gorilla Test', 'Horse Test']
end
end
When I visit the /search_foods url directly I get
'Crack', 'Cocain', 'Gorilla Test', 'Horse Test'
as my code is designed to do.
I think the issue is in that MagicSuggest, by default, sends a POST request, although I'm not sure if that's entirely relevant:
You can pass the url from which the component will fetch its JSON data.Data will be fetched
* using a POST ajax request that will * include the entered text as 'query' parameter. The results
* fetched from the server can be:
* - an array of JSON objects (ex: [{id:...,name:...},{...}])
* - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
* - a JSON object whose data will be contained in the results property
* (ex: {results: [{id:...,name:...},{...}]
Try this:
input.magicSuggest({
data: "http://localhost:3000/search_foods",
placeholder: "Search Foods...",
valueField:'idFood',
displayField:'foodName'
});
The doc states that the component expects one of the following:
* - an array of JSON objects (ex: [{id:...,name:...},{...}])
* - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
* - a JSON object whose data will be contained in the results property
* (ex: {results: [{id:...,name:...},{...}]
When you visit /search_foods you get
'Crack', 'Cocain', 'Gorilla Test', 'Horse Test'
This does not fit any of the 3 supported cases.
My suspicions about the POST request was correct.
My friend helped out so that's why I was able to fix this.
This is what I did..
Eliminated the FoodSearch Controller, because that's not needed at all.
Created a search action in my Food Controller like so:
def search
render json: ['cocain', 'crack', 'gorilla testosterone']
end
Edited my routes to a POST request instead of a get *This was the key:
resources :foods do
collection do
post :search
end
end
--- Another option, as karlipoppins suggests, is to simply change the type of request that magicSuggest makes by including the method attribute like so:
input.magicSuggest({
method: 'get',
data: "/foods/search/",
placeholder: "Search Foods...",
valueField:'idFood',
displayField:'foodName'
});
Then I wouldn't need to change the route to post.
Added this path to the data attribute in the js
data: "/foods/search/"
This will be a huge help to anyone trying to get magicSuggest to work in rails. It's a pretty damn easy setup to be honest. That one bit and the JSON formatting was the only thing that was tripping me up here.
i am using django and cloudinary direct upload to upload iamges
it is working if the form is valid.
but if my form is not valid, my page reloaded, and then the form will ask the user to upload the image again.
any way to solve this?
my code is attached below.
since i use direct upload, after an image is uploaded. it will be displayed immediately on the front end.
but when the form is invalid and the form is refreshed, the image is gone. ( after your latest update, it is true i do not need to re upload the photo again. but the photo is gone. how to display that again?)
thanks.
<script>
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
var imag_var = $.cloudinary.image(data.result.public_id, {
format : data.result.format,
version : data.result.version,
transformation : 'form_preview'
});
$('.preview').html(imag_var);
$('.status_value').text('Uploaded:' + data.result.public_id);
$('#id_cover_image').val(data.result.public_id);
return true;
});
$('.cloudinary-fileupload').bind('fileuploadprogress', function(e, data) {
$('.progress').attr({
style : "visibility:show",
});
$('.status_value').text('Uploading...');
});
</script>
The Cloudinary javascript plugin puts the preloaded resource URI in a hidden field.
See here.
From the above one sees that if the field already exists the javascript plugin will populate it. Otherwise, it will create it.
In order to retain that URI across invalid form submissions you should create a hidden field named according to the field name you specified for cloudinary_direct_upload_field and which is populated with the value from the failed submission.
Another way to work around the issue would be to submit the form using an AJAX call. That way the data on page is retained even if validation failed and resubmission is possible. See here for an example of how that may be done.
EDIT:
Version 1.0.12 of the Cloudinary Python client library now adds the hidden field when needed out of the box so resubmissions should work. See the change log.
EDIT 2:
In order to regenerate a preview image in case of form validation error you can add something like this to the javascript code you run on page load (assuming the field name in the form is "image"):
//If form validation failed have the posted preloaded URI from the earlier
//submission so we can show preview
//pull the value from the hidden field
var imageUri = $('#direct_upload input[name="image"]').val();
//preloaded image URI structure
//{resource_type}/{type}/v{version}/{filename}#{signature}
var regex = /^([^\/]+)\/([^\/]+)\/v(\d+)\/([^#]+)#([^\/]+)$/;
//if there is value and it matches the pattern:
if (imageUri && regex.test(imageUri)) {
var uriParts = regex.exec(imageUri);
var version = uriParts[3];
var filename = uriParts[4];
//reconstruct a viable source
var src = "v" + version + "/" + filename;
//generate a cloudinary image tag and add it to the 'preview' div
$(".preview").append(
$.cloudinary.image(src, {
transformation: "form_preview" //your named transformation
})
);
}
I am very new to programming and I am stumped with this problem.
I want to create am autocomplete textbox.
From what I see I would need to use json. However for the source of the json I need a url to a file script, and I do not quite get this part.
This is an example from http://jqueryui.com/demos/autocomplete/#option-source
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
Does it mean that whenever I type something in the autocomplete textbox it accesses the file in the url and the file script would change dynamically according to my input?
Also, I can only see some examples of the url file in php. Can it be done in Django? such as specifying a url as the source and link that url with a view outputting the data?
Whenever you type something in the autocomplete textbox it accesses the url to retrieve the array of data. (Use firebug or chrome developer tools while testing the demo to see the HttpRequests sent as you type)
From the documentation you linked:
"When a String is used, the Autocomplete plugin expects that string to
point to a URL resource that will return JSON data."
So yes, you can use Django as long as the URL returns JSON data.