pauluithol / backbone-tastypie Goto Github PK
View Code? Open in Web Editor NEWA small compatibility layer to make backbone.js and django-tastypie work together happily.
License: MIT License
A small compatibility layer to make backbone.js and django-tastypie work together happily.
License: MIT License
When I use backbone-tastypie to get a collection of models, only the first 20 matching results are returned due to tastypie's default limit.
After fetch
is called and these 20 models are returned, the query's meta data is stored in the collection's meta
attribute. This records the total_count
, as well as offset
, and the next
and prev
urls.
Currently, in my collections, I have to manually loop through fetch
, changing the offset
data and aggregating the results over and over until there are no more results.
Is there a better way to do this? Would it be possible to change fetch
to get all available results instead of just the first set?
I have a Product model and a Store model. Product has a hasOne relation that refers to Store
I create a Product instance, that has got 'store' attribute that has got resource_uri attribute.
But when i try to save the Product instance, i get the error:
venv/lib/python2.6/site-packages/django/db/models/fields/init.py", line 537, in get_prep_value\n return int(value)\n\nTypeError: int() argument must be a string or a number, not 'RelatedManager'\n"}
(i think that Django exptecs store_id as int, but it finds a RelatedManager )
The code of my simple app is here: https://bitbucket.org/bitliner/mdd-with-backbone-and-django
It has a index.html that display a simple Product instance, and it has a Save button that save to the db.
The backbone code is in webinf/templates/index.html, the tastypie and models are in src/DjangoBackboneRelational folder
Even when the response header has application/json
as Content-Type
, the JSON String
is sent instead of the previously parsed JSON Object
.
package.json currently contains
"main": "backbone_tastypie/tatic/js/backbone-tastypie.js",
the missing 's' in static is causing some issues
if there's a good reason for this, it can be disregarded, but why is the idAttribute
option overriden instead of always just using the url()
method?
in my use case, I've got an Option model with an Options collection, and I want to create a <select>
with the options as <options>
, and I end up with three ugly possibilities:
<option value="/api/v1/option/<id>">
which is semantically wrong<option value="<%= option.get("id") %>">
when <option value="<%= option.id %>">
would suffice and is more natural AND THEN I've got to do collection.find(function(x) { return x.get('id') == id })
instead of just collection.get(id)
idAttribute: "id"
in all of my models.. which means explicitly set things back to default.With the current url()
override in https://github.com/PaulUithol/backbone-tastypie/blob/master/backbone_tastypie/static/js/backbone-tastypie.js#L102 this shouldn't be necessary
Hi,
I don't use the same domain for the API and the web and Model.url will assume the url as the model id, and I can't set the url to use the api domain without extending this. Maybe you can add some kind of urlHost to set the correct domain.
Thanks.
Sorry for offtop, trying to integrate django tastypie with backbone, and could somebody show me how backbone-tastypie works?
Backbone-tastypie overrides several Backbone methods for compatibility with django-tastypie. These mainly have to do with Backbone.sync, building urls for models and collections, and parsing data.
I've run into some troubles using backbone-tastypie. I have a model like this:
var Movie = Backbone.Model.extend({
urlRoot: "/recipe/api/v1/movie/",
initialize: function(){
this.on('all', function(e) {
console.log(this.get('title'));
});
}
});
ar mov = new Movie({id:2});
And then I attempt to save it...
mov.save()
in which case, it should attempt to do a PUT instead of a post. But for some reason, it attempts to do a POST... giving me the following error:
POST http://127.0.0.1:8000/movie/api/v1/movie/2/ 501 (NOT IMPLEMENTED)
If I remove the tastypie-backbone.js script, the above code works properly -- requesting a PUT and updating the movie entry appropriately. Any idea on what's going on? I'm using backbone 0.9.2.
When I do a destroy in a model change me the url of the model to localhost
Backbone.Model.extend({
urlRoot: 'http://84.123.243.34/api/note/',
defaults: {
title: '',
text: ''
},
initialize: function() {
},
})
this.misCollectNotes.where({id: iId})[0].destroy();
http://localhost/api/note/152/
The GET, POST, and OPTION work well
We at VersionEye are working hard to keep up the quality of the bower's registry.
We just finished our initial analysis of the quality of the Bower.io registry:
7530 - registered packages, 224 of them doesnt exists anymore;
We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).
Sadly, your library PaulUithol/backbone-tastypie
is one of them.
Can you spare 15 minutes to help us to make Bower better?
Just add a new file bower.json
and change attributes.
{
"name": "PaulUithol/backbone-tastypie",
"version": "1.0.0",
"main": "path/to/main.css",
"description": "please add it",
"license": "Eclipse",
"ignore": [
".jshintrc",
"**/*.txt"
],
"dependencies": {
"<dependency_name>": "<semantic_version>",
"<dependency_name>": "<Local_folder>",
"<dependency_name>": "<package>"
},
"devDependencies": {
"<test-framework-name>": "<version>"
}
}
Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.
NB! Please validate your bower.json with jsonlint before commiting your updates.
Thank you!
Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!
Since there is no python besides setup.py and init.py why isn't this just an adaptor for backbone to tastypie rather than the other way around?
Just getting my feet wet with Backbone and Tastypie.
To pass my JSON into Backbone.js using Tastypie, I was doing:
def alter_list_data_to_serialize(self, request, data_dict):
return data_dict['objects']
...which just returns the contents of the 'objects' key that Tastypie usually sends. I am able to to myCollection.get(myModel.id) and have it return a Model instance using this approach.
I found your plugin because I was having issues saving a model back into Django using Backbone.js's .save() function, I gathered that Tastypie was expected the 'objects' key that I had removed.
From Tastypie resources.py put_list():
if not 'objects' in deserialized:
raise BadRequest("Invalid data sent.")
So I thought maybe this was one part of what backbone-tastypie was made to account for. I can tell so far that backbone-tastypie extracts the contents of 'objects' and passes that to the collection. So I commented out my alter_list_data_to_serialize() and added backbone_tastypie.js.
Now when I check the contents of myCollection in the javascript console after doing fetch() , it shows what looks like a normal Collection object, with a 'models' key, containing all the models that were fetched. But for some reason when I then when I check the contents of collection.models in the console, it inexplicably returns an empty array '[ ]'.
myCollection.get(myModel.id) returns 'undefined'.
myCollection.toJSON() works fine for some reason.
I've confirmed that removing backbone_tastypie.js and un-commenting my alter_list_data_to_serialize() above returns expected behavior to my Backbone Collection.
If you have a clue what's going on, any help is much appreciated!
Hi Paul,
I'm trying to implement an APP that uses both the localStorage Sync, and an Ajax sync (tastypie).
It seems like some important methods get overridden, and including tastypie seems preventing me to use other sync methods.
It's possible to explicitly select a sync method on a collection or models basis (http://stackoverflow.com/questions/5096549/how-to-override-backbone-sync), but the JS here doesn't seem to play nicely with other Sync libararies. Maybe it's the extra prototype methods like "url" and such?
Do you have an idea of how it would be possible to run both the localStorage sync along the tastypie (ajax) sync?
for some reason I get resp as null when creating a new object. Removing the check in line 25 fixed the code. Can you please tell why is it happening like this?
Thanks!
It would be nice to have both js files in the same package.
Thanks.
why not?
Super new to Backbone and super tired :)
If I have a model Player with a HasOne relation with another model Team and a collection of Player models called Players... then if I do the following from a View for Players, I get unexpected behavior...
var PlayerListView = Backbone.View.extend({
el: $('#players'),
initialize: function () {
_.bindAll(this, 'render');
this.collection = new Players;
this.collection.bind('reset', this.render);
this.collection.fetch();
},
render: function () {
_.each(this.collection.models, function (player) {
player.fetchRelated('team');
// This works
var team = player.get('team');
// This does not. It either returns the 'default' if it's defined or undefined
console.log(team.get('name'));
});
}
});
What's nerve-racking if I console.log(team), I see that it has an 'attributes' attribute, and if I drill-down into it, I see that it has a name, e.g. 'Boston Red Sox' and yet using team.get() returns 'undefined' or a default if it's defined in the Team model.
What am I missing? Do you know?
Hello,
any chances to see this repo on bower?
I can provide a component.json
as a pull request here, but I see that this repo hasn't any tags so It's a problem to register it with bower (altrough I see that backbone-relational
is on bower and has tags)
Backbone's sync is overridden specifically to do a GET upon receiving a HTTP CREATED but when that occurs and if you are using an ApiKey it is not sent along resulting in a 401 Unauthorized response from the server.
There is a fundamental problem in backbone-tastypie which assumes that a GET needs to be triggered only when doing a POST.
There is a case whereby PUTting a resource also needs to trigger an extra GET. Lets say for example we start by GETting this model, model A, from the server:
{
name: 'adam',
email: '[email protected]',
resource_uri: '/api/rest/user/45/',
manages: [
{
name: 'ben',
email: '[email protected]',
resource_uri: '/api/rest/user/1/'
}
]
}
We now add an extra "manages" entry like so:
{
name: 'adam',
email: '[email protected]',
resource_uri: '/api/rest/user/45/',
manages: [
{
name: 'ben',
email: '[email protected]',
resource_uri: '/api/rest/user/1/'
},
{
name: 'pete',
email: '[email protected]'
},
]
}
We now do a PUT on the model A. Note that this is a PUT not a POST as model A already exists, we have just added an extra nested model to the manages attribute.
Now backbone-tastypie has sucessfully PUTTed. However, a GET is not triggered. This means that the resource_uri of "pete" is never added to the client side model representation.
This poses a problem for applications that dont reload the page often. E.g., if I create "pete" and the user wants to delete it straight away. This can't be done, because the resource URI is not known.
I'm not sure if I like how you handle the creation of new objects. Why not require the user to add the always_return_data
flag to the Resource
definition and save a request per transaction?
I can submit a pull request to that effect, if you'd like.
Thanks
Why not set the csrftoken based on the cookie value if the value of Backbone.Tastypie.csrfToken is empty? If no csrftoken in cookie, then just let it be.
See : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
The current main
value in the bower.json file is backbone_tastypie/tatic/js/backbone-tastypie.js
which is wrong, and makes auto-injections fails (wiredep)
Hi i am using backbone-tastypie, i need to add authentication parameters (username and apikey) to all urls. has backbone-tastypie solution for that? or any recomendations?
I am not sure how this is supposed to work, but with the example code showed in the backbone.js document:
var Book = Backbone.Model.extend({urlRoot : '/books'});
var solaris = new Book({id: "1083-lem-solaris"});
alert(solaris.url());
We get '/books' with backbone-tastypie
. This is due to the overwritten on idAttribute
and url
.
I'm trying to Add backbone-tastypie to cdnjs.com, but their policy is to only accept tagged releases. Can you tag the current 0.2 release in github so this library can be submitted?
For more info see:
cdnjs/cdnjs#1560
Thanks!
Erik
I'm running into a weird bug that is probably the result of some gross ignorance somewhere. I have models and collections that use backbone-relational and am trying to sync them via backbone-tastypie, but I get the error
Uncaught TypeError: Cannot read property 'headers' of undefined
which is coming from the part in the overridden sync method where it is trying to "Keep headers
for a potential second request
" ...not sure where or who should be passing in the options to the sync method. Another possibly relevant detail is that I changed it so
Backbone.Model.prototype.idAttribute = "id";
since the relations for backbone-relational weren't working otherwise. However, even commenting this out, I still run into bugs. Any suggestions would be appreciated.
Hi,
Currently tastypie response for DELETE's is a 204 but backbone is waiting for something there, maybe we just need an extra if in the sync defined by backbone-tastypie.
Bye
hi sometimes i need to fetch elements independently from collections. At that moment backbone-tastypie is not making urls overriden.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.