cloudinary direct upload form is not valid, need to re upload - django

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
})
);
}

Related

Handle a click event in django-tables2

I am starting to use django-tables2 and I have added a column which should allow user to delete a record when the user clicks on the button. The code looks as follows:
class ReviewTable(tables.Table):
delete = tables.LinkColumn('review_delete', args=[tables.A('pk')], orderable=False,
empty_values=(), verbose_name='')
def render_delete(self, record):
url = static('remove.png')
href = '#'
return mark_safe('')
This basically enders the image fine in a column but all I can do is set the link to it. How can I get it to call some method where I can then filter by the record ID and delete the relevant record? Is this the correct way to do this?
When you generate HTML from code, you still have access to onclick events.
return mark_safe(''.format(href, url)
Now your delete_action can be a javascript function that gives you more control. Generated HTML is basically just any old type of HTML, so you can still use jquery event handlers with it
BTW, please note how string formatting has been used in stead of concatenation. This is more pythonic

Django - Create new object in Form, update select box and save it

I think what I'm trying to achieve is not hard, but I have no clue how to do it hehehehe !
Basically what I need is the feature that we have in Django Admin, when you are creating a new object, if you have a Foreign Key, you can add new data (opening a pop-up), save it and then the select box updates automatically.
What I have is this form:
I know that would be easy to do it with some Javascript, but my point is, Django has some rules, and as far I know, I can't add new data to a form already created, right? Otherwise Django won't validate this form. How could I achieve this?
PS: "Local" is the select box where I want to add new data. The user should be able to create a new Local on this page, instead of going to another page to do it. Thanks :)
Here your question:
I can't add new data to a form already created, right? Otherwise Django won't validate this form. How could I achieve this?
Then the answer:
you are right, django will check values match form value rules. But:
realize that your main form is invoked for twice: on GET and on POST. Between both form executions you make changes on database values trhough your new form. That means that in second main form invocation the value added to database is available:
field1 = forms.ModelChoiceField(queryset= ***1*** )
***1***: on second invocation new value is already available on field1.
Then, you don't should to be afraid about this subject, the new value will be available on form on your main form POST request.
Nothing wrong with updating the value using javascript as long the key in your new combo box has the right key in the database then it should be ok.
Call this function after you saved the last entry.
function refreshLocal(){
$.get(window.location.href, '', function(html){
// change the id to the local combox's id
var serverLocalDropBox = $(html).find('#id_local');
if (serverLocalDropBox.length){
$('#id_local').replaceWith(serverLocalDropBox);
}
})
}
If you don't want to use javascript solution, you can post the form with refresh flag and on the server side if you see that flag just don't validate and return the form as is. Since you have a new entry in the foreignkey it will automatically update the queryset to include the new entry.
function serverRefreshLocal(){
var $form = $('#your_form_id');
$form.append('<input type="hidden" name="refresh" value="true" />');
// you can use ajax submit and ajax refresh here if you don't want to leave the page
$form.submit();
}
// Server Side
def your_form_post_view(request):
if request.POST.get('refresh', 'false') == 'true':
# initial is the trick to save user input
your_form = YourForm(initial=request.POST)
context = {
'form': your_form,
}
return render(request, 'your_template.html', context)
# your view code goes here

Facebook Graph api profile picture URL

I'm trying to display the profile pic of the logged in user but for some reason the url gets changed. This is the function i've put together
function testAPI() {
FB.api('/me','GET',{"fields":"picture{url},name"},function(response) {
var url = response.picture.data.url;
console.log(url);
$("#status").html('<p>'+response.name+'</p><figure id="profilePicture"><img href="'+response.picture.data.url+'"/></figure>');
console.log(document.getElementById('status').innerHTML);
});
}
the first console log returns:
"https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p50x50/12036592_10153768750487873_8195289030629933305_n.jpg?oh=5488c4b312a1b077b68243a7998d217e&oe=56BA5DE5&gda=1454718467_89331767e8555ed196c5559340774fbb"
the second returns the correct inner html as the users name diplays but its adding amp; after the & symbols in the url so the profile pic isn't displaying. No idea how to fix this. Any help would be great thanks.
You have incorrect <img/> tag syntax, you should be using src instead of href
Change:
$("#status").html('<p>'+response.name+'</p><figure id="profilePicture"><img href="'+response.picture.data.url+'"/></figure>');
To:
$("#status").html('<p>'+response.name+'</p><figure id="profilePicture"><img src="'+response.picture.data.url+'"/></figure>');

Django - how to pass more than one primary key to the view

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()

understanding jquery ui autocomplete json

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.