Django Vuejs -- Using Axios - Issue in redering Data - django

I am trying to use VueJs inside my Django Framework ( Django as Backend) and Vuejs as Front-End. However, I am very new with axios, which I found more easier to use with VueJS Front-End. On integrating all togetherr, I didn't see anything coming up but I can see that my code is loop through the data using vueJS Developer Tools.
index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The greatest news app ever</title>
</head>
<body>
<div id="app">
<template v-for="post in posts">
<p> Hello - {{ post.title }}</p>
</template>
</div>
<script src="{% static 'vue/vue.js' %}"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="{% static 'vue/app.js' %}"></script>
</body>
</html>
app.js
new Vue({
el: '#app',
data: {
posts: []
},
methods:{
getPost: function(){
var self = this;
let url = "http://127.0.0.1:8000/api/allpost/";
axios.get(url).then((response) => {
this.posts = response.data
}, (error) => {
console.log(error);
});
}
},
mounted: function() {
this.getPost();
}
});
The Output of the code

{{ post.title }} has been the problem rendering the Data into Django Page, because Django also make use of this {{ }}. However, in a situation where someone is rendering the page with VueJS Server is doesn't apply. then, remember to add this:
delimiters: ['[[', ']]'],
<li v-for="post in posts" v-bind:key="post.id">
[[ post.title ]] <br/>
[[ post.body ]]
<hr/>
<li>
new Vue({
delimiters: ['[[', ']]'],
el: '#app',
data: {
posts: []
},
methods:{
getPost: function(){
var self = this;
let url = "http://127.0.0.1:8000/api/allpost/";
axios.get(url).then((response) => {
this.posts = response.data
}, (error) => {
console.log(error);
});
}
},
mounted: function() {
this.getPost();
}
});

Related

Why doesn't Vue show up?

I just started to learn using Vue. I wrote really simple code like the following.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<script src="https://unpkg.com/vue"></script>
<div id="app">
<h2>{{number}}</h2>
<h2>Here it is!</h2>
</div>
</body>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
number:0
}
})
</script>
</html>
However, there is no number value.
But, when I open that code just by Ctrl+O on chrome, it shows succefully!
I definitely checked network by chrome dev tool and I got successfully vue.js from https://unpkg.com/vue#2.5.22/dist/vue.js What's wrong with it?
Loading the framework in the head is a good way to start.
See the example below, it works fine in here.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<h2>{{number}}</h2>
<h2>Here it is!</h2>
<button #click="clk">click</button>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
number: 0
},
methods: {
clk(){
this.number++;
}
}
})
</script>
</body>
</html>
I thought you should return an object from a function for data.
data : function() {
return {
number : 0
};
}

How can i send a post request using vue to django without getting a 403 error?

Im trying to send information using a post request of Vue, but every time i try i get an error 403 58
my django service is ok , i think that the problem is for the csrf token but i dont know how to send it with vue
var vue = new Vue({
el:"#app",
data: {
nombre:"",
apellido:"",
password:""
},
methods:{
enviar:function () {
data = {
"nombre":this.nombre,
"apelldio":this.apelldio,
"password":this.password
};
this.$http.post("http://localhost:8000/usuarios\\",data).then(function (data, status, request) {
if(status ==200){
console.log(data);
}
},function () {
console.log("Error");
});
}
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
</head>
<body>
<h1>Insertar un nuevo usuario </h1>
<table id = "app">
<tr><td>Nombre:</td><td><input type="texte" class="form-control" v-model="nombre"></td></tr>
<tr><td>Apellido:</td><td><input type="texte" class="form-control" v-model = "apellido"></td></tr>
<tr><td>Password:</td><td><input type="texte" class="form-control" v-model="password"></td></tr>
<tr> <td> <button type="button" id = "enviar" class="btn btn-info" #click="enviar">Enviar</button></td></tr>
</table>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
{% csrf_token %}
<!-- here goes the scripts of vue and vue resource!>
You could use a method that involves fetching the csrf token with javascript and then passing it to the POST request as a header as mentioned here in Django documentation. In that link there is also examples about fetching the csrf token value.
Also, if the endpoint does not require this kind of protection you can disable it like in this example.
You can use something like this:
{% csrf_token %}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
<script>
var csrf = document.querySelector('[name="csrfmiddlewaretoken"]').value;
Vue.http.interceptors.push(function (request, next) {
request.headers['X-CSRF-TOKEN'] = csrf;
next();
});
// Or maybe
Vue.http.headers.common['X-CSRF-TOKEN'] = csrf;
</script>
You can also use it like this, for example:
<script>
var csrf = '{{ csrf_token }}';
Vue.http.headers.common['X-CSRF-TOKEN'] = csrf;
// Or other way
// Vue.http.interceptors.push(...);
</script>
Note: I'm no django developer but gave you the basic idea, so check the doc for more info.

Sample task application with drag and drop

app.js
App = Em.Application.create();
App.IndexRoute = Em.Route.extend({
model: function(){
return {
newTasks: Em.A([
{id: 1, name: "Task 1"},
{id: 2, name: "Task 2"},
{id: 3, name: "Task 3"}
]),
inProgressTasks: Em.A([
{id: 4, name: "Task 4"},
{id: 5, name: "Task 5"}
]),
doneTasks: Em.A([
{id: 6, name: "Task 6"}
])
};
}
});
App.IndexController = Em.Controller.extend({
actions: {
moveTask: function(taskID, from, to){
var model = this.get('model');
var task = model[from].findProperty('id', parseInt(taskID, 10));
model[to].pushObject(task);
model[from].removeObject(task);
}
}
});
App.TaskContainerComponent = Em.Component.extend({
classNames: ['col-xs-4', 'taskContainer'],
isOverdrop: false,
classNameBindings: ['isOverdrop:isOverdrop'],
setOverdropIfNotOriginator: function(event, valueToSet){
var data = JSON.parse(event.dataTransfer.getData('text/data'));
if(data.stage !== this.get('stage')) {
this.set('isOverdrop', valueToSet);
}
},
dragEnter: function(event) {
this.setOverdropIfNotOriginator(event, true);
},
dragLeave: function(event){
this.setOverdropIfNotOriginator(event, false);
},
dragOver: function(event){
this.setOverdropIfNotOriginator(event, true);
event.preventDefault();
},
drop: function(event) {
var data = JSON.parse(event.dataTransfer.getData('text/data'));
if(data.stage === this.get('stage')) return;
// from: data.stage, to: this.get('stage')
this.sendAction('action', data.id, data.stage, this.get('stage'));
this.set('isOverdrop', false);
}
});
App.DragTaskComponent = Em.Component.extend({
dragStart: function(event) {
var data = { id: this.get('task.id'), stage: this.get('stage')};
event.dataTransfer.setData('text/data', JSON.stringify(data));
}
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mini Scrumboard</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/x-handlebars" data-template-name="index">
<div class="contents">
<div class="row">
{{ task-container containerTitle="New" stage="newTasks" tasks=model.newTasks
action="moveTask" on="drop"}}
{{ task-container containerTitle="In Progress" stage="inProgressTasks"
tasks=model.inProgressTasks action="moveTask" on="drop" }}
{{ task-container containerTitle="Done" stage="doneTasks" tasks=model.doneTasks
action="moveTask" on="drop" }}
</div>
<br>
<br>
</div>
</script>
<!-- Properties: task, stage -->
<script type="text/x-handlebars" id="components/drag-task">
<div class="task" draggable="true">
{{task.name}}
</div>
</script>
<!-- Properties: containerTitle, stage, tasks -->
<script type="text/x-handlebars" id="components/task-container">
<h3>{{containerTitle}}</h3>
{{#each task in tasks}}
{{drag-task task=task stage=stage}}
{{/each}}
</script>
<script src="js/libs/jquery-1.10.2.js"></script>
<script src="js/libs/handlebars-1.1.2.js"></script>
<script src="js/libs/ember-1.5.1.js"></script>
<script src="js/app.js"></script>
<!-- to activate the test runner, add the "?test" query string parameter -->
<script src="tests/runner.js"></script>
</body>
</html>
I have this working perfectly fine on my local box, but it is errorring out on jsbin.
http://emberjs.jsbin.com/movex/4/edit?html,css,js,output
I am guessing that the issue has to do with parsing the output from the drag and drop, but have no clue where to go with this.
Any help would be greatly appreciated...
UPDATE: The JSBin version even works fine on the FF on the Mac, but not on Safari or Chrome... :(
The reason it was not working is because of the very unexpected way that the drag and drop specifications work. The problem is that in the drag, dragEnter, dragLeave, dragOver and dragEnd events the dragTransfer data is in protected mode. Which again according to the spec means.
the data itself is unavailable and no new data can be added.
It seems as though Mozilla exercised some common sense and didn't implement drag and drop in compliance with the spec. Which explains why it was working in Firefox for you, but nowhere else.
To get your jsbin working I added a theData element to your index controller and did the setting and getting of the JSON values against that.
Here is the working version. http://emberjs.jsbin.com/dasonona/1/edit

Ember JS app shows blank page

I'm creating a simple Ember JS app based loosely on the Beginner's Guide on the website. However, I can't seem to get anything to render on the page. When I check the Ember Inspector my routes are all present and I don't see any errors so it's not immediately clear where the problem is.
Here is the html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Coin</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<script type="text/x-handlebars">
<div>Hello</div>
{{outlet}}
</script>
<script type="text/x-handlebars" id="accounts">
<div>accounts</div>
<div class="col-md-2">
<ul class="nav nav-pills nav-stacked">
{{#each}}
<li>account link {{#link-to 'account' this}}{{name}}{{/link-to}}</li>
{{/each}}
</ul>
</div>
<div class="col-md-10">
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" id="account">
<ul>
{{#each}}
<li>{{comment}}</li>
{{/each}}
</ul>
</script>
<script src="js/libs/jquery-1.10.2.js"></script>
<script src="js/libs/handlebars-1.1.2.js"></script>
<script src="js/libs/ember-1.4.0.js"></script>
<script src="js/app.js"></script>
<script src="dist/js/bs-core.min.js"></script>
<script src="dist/js/bs-nav.min.js"></script>
<!-- to activate the test runner, add the "?test" query string parameter -->
<script src="tests/runner.js"></script>
</body>
</html>
And here is my app.js file:
App = Ember.Application.create();
App.Router.map(function() {
this.resource('accounts');
this.resource('transactions', { path: ':accounts_id' });
})
App.AccountsRoute = Ember.Route.extend({
model: function() {
return accounts;
}
})
App.TransactionsRoute = Ember.Route.extend({
model: function() {
return transactions;
}
})
var accounts = [{
id: 1,
name: 'Account 1',
}, {
id: 2,
name: 'Account 2'
}];
var transactions = [{
id: 1,
id_account: 1,
amount: 12,
comment: 'blah'
}, {
id: 2,
id_account: 1,
amount: 5,
comment: 'blah2'
}, {
id: 3,
id_account: 2,
amount: 98,
comment: 'blah4'
}];
The one thing that renders properly on the page is the "Hello" in the application template. Nothing shows in the {{outlet}} when I navigate to #/accounts or any of the other defined routes. And in fact, when I add #/accounts in the url even my "Hello" disappears.
Is there something obvious that I'm overlooking? I'm new to Ember so I'm sure it's something silly but I can't figure out where the problem is from the documentation.
edit: I'm using Ember v1.4.0 linked directly from the website and I have checked "Allow access to file urls" in Ember Inspector.
I made a working version of what you started in this ember jsbin
What I noticed you were doing wrong was by trying to link to a non-existing route with this {{#link-to 'account' this}}. You didn't define the account route that I notice you want to receive a parameter. However I think you want to send the id of the current item in the iteration. So you can simply do that by changing this into {{#link-to 'account' id}}.
So 2 important modifications to get to something working was to add the route and to fix the param of the link-to helper. Then I just assumed that you want to show transactions as well and fixed that as well.
Hope this helps.

The bound view does not update upon saving when using ember-model RESTAdapter.

I am exploring using ember-model (https://github.com/ebryn/ember-model), as an alternative to ember-data in my ember.js application. I don't have enough rep yet to create a new tag, but if so, I'd create ember-model.js to avoid confusion.
The desired behavior is to display a simple list of records and display a form to create new records via a RESTful rails API, Using GET and POST.
This worked smoothly with the Fixture Adaptor inside ember-model. Upon creation, as expected, the new record is pushed onto the Fixture array and the browser automatically updates to reflect the new record.
Using the ReST Adaptor, I was able to display the list and create a new record. However, the newly created record, which is bound to a template, will not update unless I hit the refresh button on the browser. And now I wonder what I might be doing wrong.
I dug around StackOverflow and elsewhere before I posted. I'm going to dig into the source next, but I thought I'd ask to see if anyone else has any insights.
Thank you, good people of Stack Overflow.
This is my app.js:
window.Dash = Ember.Application.create({
LOG_TRANSITIONS: true
});
Dash.Router.map(function() {
// put your routes here
this.resource('apps', function() {
this.route('add');
this.resource('app', { path: ':app_id' });
});
});
Dash.IndexRoute = Ember.Route.extend({
//temporary redirect to games list
redirect: function () {
this.transitionTo('apps');
}
});
Dash.AppsRoute = Ember.Route.extend({
model: function() {
return Dash.App.find();
}
});
Dash.AppsAddController = Ember.Controller.extend({
save: function() {
var name = this.get('name');
var id = this.get('id');
var account_id = this.get('account_id');
var auth_id = this.get('auth_id');
var state = Dash.AppState.selectedState;
var store_type = Dash.AppPlatform.selectedPlatform;
var store_app_id = this.get('store_app_id');
var download_url = this.get('download_url');
var newApp = Dash.App.create({
name: name,
id: id,
auth_id: auth_id,
state: state,
store_type: store_type,
store_app_id: store_app_id,
download_url: download_url
});
newApp.save();
}
});
Dash.AppPlatform = Ember.ArrayController.create({
selectedPlatform: null,
content: [
Ember.Object.create({id: 'itunes', name: 'iOS'}),
Ember.Object.create({id: 'android', name: 'Google Play'}),
Ember.Object.create({id: 'amazon', name: 'Amazon Appstore'}),
]
});
Dash.AppState = Ember.ArrayController.create({
selectedState: null,
content: [
Ember.Object.create({name: 'test'}),
Ember.Object.create({name: 'production'})
]
})
Dash.App = Ember.Model.extend({
id: Ember.attr(),
name: Ember.attr(),
auth_id: Ember.attr(),
state: Ember.attr(),
store_type: Ember.attr(),
store_app_id: Ember.attr(),
download_url: Ember.attr(),
});
Dash.App.adapter = Ember.RESTAdapter.create();
//hardcoding account id for now
Dash.App.url = 'http://localhost:3000/accounts/980190962/apps';
Dash.App.collectionKey = 'apps';
This is index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dashboard</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h2>Dashboard</h2>
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="apps">
{{#linkTo 'apps.add' }}Add an App{{/linkTo}}
<h3>Apps List</h3>
{{#if model}}
<ol>
{{#each model}}
<li>{{#linkTo 'app' this}}{{name}}{{/linkTo}}</li>
{{/each}}
</ol>
<div>{{outlet}}</div>
{{else}}
<p>You have no Apps.</p>
{{/if}}
</script>
<script type="text/x-handlebars" data-template-name="apps/index">
<p>Click a game to Edit or click Add to enter a new App.</p>
</script>
<script type="text/x-handlebars" data-template-name="app">
<div>
Name: {{name}}<br />
ID: {{id}}<br />
Account ID: {{account_id}}<br />
AuthID : {{auth_id}}<br />
Test Mode?: {{state}}<br />
Store Type: {{store_type}}<br />
Store App ID: {{store_app_id}}<br />
Download URL: {{download_url}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="apps/add">
<p><label for="name">Name:</label><br />{{view Ember.TextField valueBinding='name'}}</p>
<p><label for="id">ID:</label><br />{{view Ember.TextField valueBinding='id'}}</p>
<p><label for="account_id">Account ID:</label><br />{{view Ember.TextField valueBinding='account_id'}}</p>
<p><label for="auth_id">Auth ID:</label><br />{{view Ember.TextField valueBinding='auth_id'}}</p>
<p><label for="state">Test Mode:</label><br />{{view Ember.Select contentBinding='Dash.AppState' valueBinding='Dash.AppState.selectedState' optionValuePath="content.name" optionLabelPath="content.name"}}</p>
<p><label for="store_type">Store Type:</label><br />{{view Ember.Select contentBinding='Dash.AppPlatform' valueBinding='Dash.AppPlatform.selectedPlatform' optionValuePath="content.id" optionLabelPath="content.name"}}</p>
<p><label for="store_app_id">Store App ID:</label><br />{{view Ember.TextField valueBinding='store_app_id'}}</p>
<p><label for="download_url">Download URL:</label><br />{{view Ember.TextField valueBinding='download_url'}}</p>
<p><button {{action 'save'}}>Save</button></p>
</script>
<script src="js/libs/jquery-1.9.1.js"></script>
<script src="js/libs/handlebars-1.0.0-rc.4.js"></script>
<script src="js/libs/ember-1.0.0-rc.6.js"></script>
<script src="js/libs/ember-model.js"></script>
<script src="js/app.js"></script>
</body>
</html>
It won't automatically work this way. Your content array in the AppState controller is just a static array with items in it. You'd have to do something like this
this.controllerFor('Apps').get('content').pushObject(newApp) to see it reflect in the UI.
Your Apps controller will be an ArrayController because the Apps route's model function returned an array.