Backbone Collection - django

I was trying to make a Backbone Application with Django at its backend. I was following a Backbone tutorial. I used the following code:
Code
<!doctype html>
<html lang = "en">
<meta charset = "utf-8">
<title>IstreetApp</title>
<link rel="stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Book Manager</h1>
<hr />
<div class="page"></div>
</div>
<script type = "text/template" id = "booklist.template">
</script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.10/backbone-min.js"></script>
<script>
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.url = 'http://backbonejs-beginner.herokuapp.com' + options.url;
});
var Books = Backbone.Collection.extend({
url: '/books'
});
var BookList = Backbone.View.extend({
el: '.page',
render: function () {
var that = this;
var books = new Books();
books.fetch({
success: function(books) {
var template = _.template($('#booklist.template').html(), {books: books.models});
that.$el.html(template);
}
})
}
});
var Router = Backbone.Router.extend({
routes: {
'': 'home'
}
})
var bookList = new BookList();
var router = new Router();
router.on('route:home', function () {
bookList.render();
});
Backbone.history.start();
</script>
</body>
</html>
Since the collection is not defined, the success code doesn't execute. I suppose the collection data should come from the server through Django but I am not sure how and in what form. Kindly help. I am pretty much new to backbone and Django.

When you call fetch on your collection, it makes an AJAX request to:
http://backbonejs-beginner.herokuapp.com/books
However, there is no API set up there. Either one of two things needs to happen:
1) you need to modify your code to point to a different URL, one that does have an existing API (perhaps whatever tutorial you are using has such an API)
2) you need to create such an API yourself on yoursever.com (and then make your Backbone code point to that API's URL instead)
Without a server to support it, operations like save and fetch and such in Backbone simply cannot function.
As a side note, Django is a web site framework. While you can use it to create server-side APIs, that's not really Django's focus. Because of this, several good third party libraries exist for doing RESTful APIs (ie. the kind that Backbone likes) in Django; personally I'd recommend either Django REST Framework (I use it and it works great) or TastyPie (never used it, but it's very popular).

When using a backbone collection you need to return a json array of objects from your api url (http://backbonejs-beginner.herokuapp.com/books)
Example
{[{"name":"bookname", "publisher": "penguin"}, {"name":"bookname", "publisher":"penguin"}]}
You'll also want a model for your collection. A model would look like this
Example:
var Book = Backbone.Model.extend({
defaults: {
"name": "",
"publisher": ""
}
});
The way that the collection works is by parsing the json array and turning each object in the array in to a model that you specific (in this instant an individual book with values for the name and publisher).
When you make a .fetch() on your model you are making a GET request, so make sure that your http://backbonejs-beginner.herokuapp.com/books url is prepared to receive GET requests and respond with the json data in the format I specified up top.

Related

How to display PDF in Camunda Embedded form

I have seen many discussions on how to display a PDF file within a embedded form ( User Task ) But realised camunda does not support this. Are there any solutions?
I have tried using IFrame, Object, embed , and directly linking to a variable did not work ?
My solution is to fetch the variable and convert to a blob as follows:
HTML
<embed class="col-sm-12" style="height:100vh;width:100%" type="application/pdf" id="pdf-frame">
JS
<script cam-script type="text/javascript">
camForm.on('form-loaded', function () {
fetch("http://localhost:8181/camunda/api/engine/engine/default/task/" + camForm.taskId + "/variables/ACORD_FORM/data").then(function (response) {
return response.blob();
}).then(function (myBlob) {
var objectURL = URL.createObjectURL(myBlob);
document.querySelector('#pdf-frame').src = '';
document.querySelector('#pdf-frame').src = objectURL;
objectURL = URL.revokeObjectURL(myBlob);
});
});
</script>

Django: how to get a javascript value from template to view?

I am currently using Django framework.
I would like to get the value of a javascript value wrote in an html file.
I would like to be able to display it in my view file
Here is my html file from the folder templates:
<script>
var toto = "javascript";
document.write(toto)
</script>
This is my view file:
def javascript(request):
# print the javascript value here
return render(request, "rh/javascript.html")
Thank you for your help !
You have to consider that your script runs on the client-site whereas the view function runs on the server-side. This is one main challenge when it comes to shifting variables from one end to the other.
To make a long story short:
You will have to make a http request from the client-site (for example using jQuery AJAX) to call the view. Then you can pass the variable via AJAX to the view function and use it for further logic.
Example:
your.html
<script type="text/javascript">
// A CSRF token is required when making post requests in Django
// To be used for making AJAX requests in script.js
window.CSRF_TOKEN = "{{ csrf_token }}";
</script>
<div id="variable">Variable</div>
javascript
(function($) {
// trigger the logic on click of the container
$('#variable').on('click', function() {
// assign variable
var variable_for_view = $(this).html();
// make http request using AJAX
$.ajax({
type: 'post',
url: '/your_url/', // this is the mapping between the url and view
data: {
'variable': variable, // ! here is the magic, your variable gets transmitted to the server
'csrfmiddlewaretoken': window.CSRF_TOKEN
},
success: function(data) {
print(sliced_variable)
},
});
});
}(jQuery));
views.py
def your_view(request):
# Assign variable from AJAX request
variable = request.POST.get('variable')
print(variable)
variable.slice(3)
context = {
'sliced_variable': variable
}
return render(request, 'your.html', context)

Power BI Premium - embed using Power BI API and javascript not working like previous way

Earlier I used to use 'loadReport' from javascript which is not working with new PBI Premium, e.g. the below is not working anymore & it always says "This content isn't available". BTW this is still working for PBI embedded reports.
<html>
<body>
<iframe id="iFrameEmbedReport"></iframe>
</body>
<script type="text/javascript">
window.onload = function () {
var iframe = document.getElementById('iFrameEmbedReport');
iframe.src = 'https://app.powerbi.com/reportEmbed?reportId=******-088f-4967-***-279bd5a**df&groupId=*****-****-4033-862d-1cd4f4fa72c1';
iframe.onload = function()
{
var m = {
action: 'loadReport',
accessToken: 'H4s*****'
};
message = JSON.stringify(m);
iframe = document.getElementById('iFrameEmbedReport');
iframe.contentWindow.postMessage(message, "*");
};
};
</script>
</html>
But if we use powerbi.js with the same configs its working fine (below)
<html>
<body>
<div id="reportContainer"></div>
</body>
<script src="https://microsoft.github.io/PowerBI-JavaScript/demo/node_modules/jquery/dist/jquery.js"></script>
<script src="https://microsoft.github.io/PowerBI-JavaScript/demo/node_modules/powerbi-client/dist/powerbi.js"></script>
<script type="text/javascript">
window.onload = function () {
var accessToken = '******************';
var embedUrl = 'https://app.powerbi.com/reportEmbed?reportId=**********&groupId=**********';
var embedReportId = '*****-088f-****-aa2d-279bd5a662df';
var models = window['powerbi-client'].models;
var config = {
type: 'report',
tokenType: models.TokenType.Embed,
accessToken: accessToken,
embedUrl: embedUrl,
id: embedReportId,
permissions: models.Permissions.All,
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true
}
};
var reportContainer = $('#reportContainer')[0];
var report = powerbi.embed(reportContainer, config);
}
</script>
</html>
Not able to figure out what has changed. I really don't want to include powerbi.js in my application if not needed. I know I have a working copy but really need to understand what has changed and if there is any way I can avoid powerbi.js. End goal is to use the first approach in UWP App.
Thanks
The main thing that's changed in the 2 approaches is the property TokenType.Embed which is not available in the 'old way', i.e. 'loadReport' message format.
This is a deprecated way of communicating with embedded entities from Power BI, and all users are encouraged to write their code against the new and maintained Javascript SDK: https://microsoft.github.io/PowerBI-JavaScript/
The 'loadReport' way work for backward compatibility concerns but you won't be able to write new code in new methods using this way.

How to redirect whole page when remote posts to iframe in Django

I am working on using Paypal payments advanced embedded / hosted checkout pages in my django site. I display an iframe for the paypal payment page, I submit the request, and it posts back to my site.
The view that handles the paypal response uses
response = redirect("shop_complete")
return response
but this makes my whole response page pop up in the iframe. I could just use a template that would look all right in that spot, but I would like to update the cart and the payment step at the same time. Is there anyway to make that response redirect the whole browser instead of just the frame?
So, my solution wound up being to add an intermediary page that consist entirely of a script to redirect the top level of the browser. I got this script from
JavaScript post request like a form submit
<body>
<script type="text/javascript">
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "_top" )
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
};
window.onload = post_to_url('{% url "shop_paypal_redirect" %}',
{csrfmiddlewaretoken: '{{ csrf_token }}',
result: '{{ result }}'});
</script>
</body>

Remember preferable language

I've made a simple website for my daughter.
It is in Dutch and for every page there is a English version as well.
Dutch URL: nl/index.html
English URL: eng/index.html
What I would like to do is give the visitor the option to set one language as preference. So if they come to this site the next time they will automatically linked to the preferable page.
I know this can be done with a cookie and saw the explanation on this forum ( How to remember the currently clicked url? javascript?PHP? ).
I've tried to make this work but apparently I am doing something wrong?
Can somebody guide me through step by step? That would be great!
Kind regards,
Jurgen
If you are familiar with jQuery you can use the cookies plug-in to persist the user's language choice and redirect him to the appropriate page every time he comes back to your site. Bellow is a sample code that uses two buttons to set the language:
First you declare the jQuery scripts (I use to store them in a Script folder, hence the following):
<script type="text/javascript" src="../Script/jquery-1.7.2.js"></script>
<script type="text/javascript" src="../Script/jquery.cookie.js"></script>
Then you define the page ready event like this:
$(function () {
var url = 'your_url';
var english_page = 'eng/index.html';
var dutch_page = 'nl/index.html';
if ($.cookie('default_page') != null) {
if (window.location.href != url + '/' + $.cookie('default_page')) {
window.location.href = url + '/' + $.cookie('default_page');
}
}
$('#set_english_butt').click(function () {
$.cookie('default_page', english_page, { expires: 999 });
alert('English was set as the default language');
});
$('#set_dutch_butt').click(function () {
$.cookie('default_page', dutch_page, { expires: 999 });
alert('Dutch was set as the default language');
});
});
Which is hooked to some html buttons in you page:
<div>
<span>Select your language:</span>
<button id="set_english_butt">English</button>
<button id="set_dutch_butt">Dutch</button>
</div>