Search code examples
jquerydjangotastypie

Sending data to tastypie raises 401


i tried to send some data to a tastypie poc.

i've designed my model:

class Category(models.Model):
    name = models.CharField(max_length=30)
    icon = models.FileField(upload_to="media/img/wish-icons/")


class Wish(models.Model):
    content = models.CharField(max_length=140)
    category = models.ManyToManyField('wishes.Category', blank=True, null=True)
    lat = models.FloatField('Latitude', blank=True, null=True)
    lon = models.FloatField('Longitude', blank=True, null=True)

i've a related api.py:

class CategoryResource(ModelResource):
    class Meta:
        queryset = Category.objects.all()
        resource_name = 'category'
        fields = ['name', 'icon']


class WishResource(ModelResource):
    category = fields.ToManyField(CategoryResource, 'category', full=True)

    class Meta:
        queryset = Wish.objects.all()
        resource_name = 'wish'
        authorization = Authorization()
        list_allowed_methods = ['get', 'post']

i can send GET request to get a list or a detail but when i want to send data with jQuery and ajax, Firebug returns me a 401 error.

I did like the example here but something goes wrong and i don't know where. It's not a cross domain request, front and tastypie have to same origin.

My ajax request looks like this:

var data = JSON.stringify({
  "content": "This will prbbly be my lst post."
});
$.ajax({
  url: 'http://127.0.0.1:8000/api/v1/wish/',
  type: 'POST',
  contentType: 'application/json',
  data: data,
  dataType: 'json',
  processData: false
});

Solution

  • everything works. I really don't know how, i played with authentication, authorization, filed types, adding/removing things and finally this is my valid app.py

    class CategoryResource(ModelResource):
    
        class Meta:
            queryset = Category.objects.all()
            resource_name = 'category'
            authorization = Authorization()
    
    
    class WishResource(ModelResource):
        categories = fields.ToManyField('wishes.api.CategoryResource', 'category', null=True, full=True)
    
        class Meta:
            queryset = Wish.objects.all()
            resource_name = 'wish'
            authorization = Authorization()