GithubHelp home page GithubHelp logo

pauluithol / backbone-tastypie Goto Github PK

View Code? Open in Web Editor NEW
467.0 467.0 81.0 767 KB

A small compatibility layer to make backbone.js and django-tastypie work together happily.

License: MIT License

Python 0.37% JavaScript 98.36% CSS 1.26%

backbone-tastypie's People

Contributors

anttihirvonen avatar areski avatar asaayers avatar dhui avatar jengdal avatar jordanvg avatar maraujop avatar pauluithol avatar smileychris avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

backbone-tastypie's Issues

Collections contain unused meta data, limiting collection results

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?

Problem saving a model related to another model

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

Typo in package.json

package.json currently contains

"main": "backbone_tastypie/tatic/js/backbone-tastypie.js",

the missing 's' in static is causing some issues

don't override the default idAttribute

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:

  • end up with a bunch of <option value="/api/v1/option/<id>"> which is semantically wrong
  • do <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)
  • set 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

How does it work?

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.

PUT is handled as a POST instead, resulting in server error

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.

DELETE change url

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

[enhancement] Add missing bower.json.

Hey, maintainer(s) of PaulUithol/backbone-tastypie!

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!

Problem accessing Models in Collection

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!

Compatibility with other Backbone Sync (localStorage, original)

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?

resp is null

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!

Can't get at attributes from fetchRelated() model

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?

Bower support

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)

ApiKey isn't sent with extra GET during Backbone.sync

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.

Putting a model with new nested resources wont update resource_uri

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.

2 requests per 'create'

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?

More here.

I can submit a pull request to that effect, if you'd like.

Thanks

Wrong "main" value in bower.json

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)

Any solution for authentication types?

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?

Cannot generate URL correctly

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.

options.headers undefined when trying to sync relational model

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.