I have used django-tastypie using GET,POST,PUT,DELETE methods , they are working smoothly when both client and server are from same domain but if I make a request from different domain nothing happened at all.
Any clue?
models.py
from django.db import models
class Entry(models.Model):
title = models.CharField(max_length=30)
body = models.CharField(max_length=40)
pub_date = models.DateField()
slug=models.CharField(max_length=30)
resources.py
from django.contrib.auth.models import User
from tastypie.authorization import Authorization
from tastypie import fields
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from myapp.models import Entry
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
filtering = {
'username': ALL,
}
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
resource_name = 'entry'
authorization = Authorization()
filtering = {
'user': ALL_WITH_RELATIONS,
'pub_date': ['exact', 'lt', 'lte', 'gte', 'gt'],
}
urls.py
from django.views.generic.simple import direct_to_template
from django.conf.urls.defaults import *
from tastypie.api import Api
from myapp.resources import EntryResource, UserResource
v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(EntryResource())
urlpatterns = patterns('',
# The normal jazz here...
(r'^api/', include(v1_api.urls)),
(r'^basic/$', direct_to_template, {'template': 'todos/test.html'})
)
And template file is as below
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
jQuery(document).ready(function($) {
var data = JSON.stringify({
"body": "This will prbbly be my lst edited post.",
"pub_date": "2011-05-22T00:46:38",
"slug": "another-post",
"title": "Another Post",
});
$.ajax({
url: "http://localhost:8000/api/v1/entry/1/?format=json",
type: 'PUT',
contentType: 'application/json',
data: data,
dataType: 'json',
processData: false,
success:function(data) {
alert(data);
},
error : function(data){
alert('error')
},
})
})
</script>
</head>
<body>
body content goes here
</body>
</html>
now when i run http://localhost:8000/basic it working perfectly for CRUD
later i installed apache server and copied that basic.html. When I run http://localhost:81/basic.html then json data are not accepted by server. I have run both apache and python server parallelly.
You will need to set your client and your server to do cross domain ajax.
In jquery, you would do set
crossDomain : truein your$.ajax()call(see http://api.jquery.com/jQuery.ajax/)
On the server side, you will need to set a couple of accept headers
http://enable-cors.org/
You can find out more about cross domain request by looking up the CORS specification:
http://www.w3.org/TR/cors/