Reputation: 9087
Whenever I do a model.destroy() with Backbone, it tries to do a DELETE request on the following URL:
http://localhost:8000/api/v1/item/?format=json
Since I am doing a destroy on a model, I would expect that the ID of the model should be passed, so the URL to do a DELETE request on would be this:
http://localhost:8000/api/v1/item/8/?format=json
where the ID is specified. Because of the lack of ID, and my use of tastypie, all items get deleted. How do I make it so that the URL contains the ID of the item that I wish to delete?
Upvotes: 0
Views: 216
Reputation: 434965
I'm guessing that your model looks something like this:
var M = Backbone.Model.extend({
url: '/api/v1/item/?format=json',
// ...
});
The url
for a model is supposed to be a function but, since it ends up going through the internal getValue
function, a string will also "work"; if you check the source I linked to, you'll see why a string for url
would give you the results you're seeing.
The solution is to use a function for url
as you're supposed to:
url
model.url()
Returns the relative URL where the model's resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form:
"/[collection.url]/[id]"
, falling back to"/[urlRoot]/id"
if the model is not part of a collection.
You'd probably want something like this:
url: function() {
if(this.isNew())
return '/api/v1/item/?format=json';
return '/api/v1/item/' + encodeURIComponent(this.id) + '/?format=json';
}
or this:
url: function() {
if(this.isNew())
return '/api/v1/item/?format=json';
return '/api/v1/item/' + encodeURIComponent(this.get('id')) + '/?format=json';
}
Upvotes: 2