Rectangle 27 1

Seems like tasty doesn't allow you to filter by virtual field, when the field attribute is represented by lambda.

You can make it work with some modifications:

class PostCategory(models.Model):
    post = models.ForeignKey(Post, related_name='categories')
    category = models.ForeignKey(Category)


class PostResource(ModelResource):
    user = fields.ToOneField(ProfileResource, 'user', full=True)
    categories = fields.ToManyField(PostCategoryResource, 'categories', full=True)

    class Meta:
        queryset = Post.objects.all()
        resource_name = 'post'
        filtering = {
            # filter by user
            'user': ALL_WITH_RELATIONS,

            #filter by category id
            'categories': ALL_WITH_RELATIONS,
            'category': ALL,
            'id': ['exact'],
        }

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

django - Tastypie ManyToMany filter - Stack Overflow

django tastypie
Rectangle 27 7

You can filter fields using lambda bundle attribute showing table name and field name.

tags = fields.ToManyField('django_app.api.TagsResource', attribute=lambda bundle: bundle.obj.tags.filter(tags__deleted=0))

python - Tastypie, filtering many to many relationships - Stack Overfl...

python django tastypie
Rectangle 27 1

Wow... I've been looking all day for this! the "attribute" is exactly what I was looking for. I almost started hacking at my models to do the filtering there out of despair.

This field also has special behavior when dealing with attribute in that it can take a callable. For instance, if you need to filter the reverse relation, you can do something like:

subjects = fields.ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal'))

python - Tastypie, filtering many to many relationships - Stack Overfl...

python django tastypie
Rectangle 27 2

You can extend your attribute argument you've passed to the data field with a full-scale function and reuse the DataResource:

def filter_data_items(bundle):
    res = DataResource()
    new_bundle = Bundle(request=bundle.request)
    objs = res.obj_get_list(new_bundle)
    return objs.filter(parent_id=bundle.obj.pk)

res.obj_get_list handles building and applying filters as defined per your DataResource. You just need to filter it futher on parent_id.

python - Django Tastypie - Filtering ToManyField resource with URL par...

python django python-2.7 tastypie
Rectangle 27 1

You haven't provided details of your error, so i can just guess what's wrong!so if you provide more details I'll delete it if it is wrong! maybe the problem is that you haven't set MEDIA_ROOT in your settings.py file like bellow:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Hi @iman-mirzadeh, it is a 404 error. I saw what you mentioned somewhere else and tried it to to avail. I added it in again and you specified and was not able to see the image in the browser. Thanks for responding!

python - Using django ImageField with Tastypie - Stack Overflow

python django django-models tastypie
Rectangle 27 2

When deploying via WSGI using print statement can raise IOErrors. Try to comment them out or redirect the output.

Append a slash

url = 'http://127.0.0.1:8000/api/user/login/'

Well, instead of using print statement/function, OP should rather rely on logging module. More about print vs. logging is here: stackoverflow.com/a/17553247/548696

django - HTTP 500 error on POST - Stack Overflow

django tastypie
Rectangle 27 4

I managed to solve the issue by changing the field in BlogPostResource to the following:

class BlogPostResource(ModelResource):

    comments = fields.ToManyField("resources.CommentResource",
        attribute=lambda bundle: bundle.obj.comments.all().order_by("published"))

If I do this the comments are not paginated

python - Is it possible to sort elements in a ToManyField attribute us...

python django rest tastypie
Rectangle 27 4

for one_uri in uris:

That's where the "Bundle" object is not iterable is coming from. If you want to iterate over those fields as resource_uris, remove full=True from those FK fields.

If you want to keep them as full=True, you'll need to update your validation to either handle bundles for those fields or exclude them from the validation by using exclude in your form Meta class:

class ModelFormValidation:
    ...

    class Meta:
        exclude = (
            authors,
            posts,
            cover_photo            
        )

I'm 99% sure that those fields are Bundle objects, unless they're present in the PATCH request. I'm finding hard to bare with tastypie providing different object types depending on data in PATCH request.

api - Django Tastypie PATCH throws "'Bundle' object is not iterable" e...

django api rest patch tastypie
Rectangle 27 2

You could also try adding an ordering in the actual Comment Model (not in the tastypie Comment ModelResource):

class Comment(models.Model):
    blog_post = models.ForeignKey(BlogPost, related_name="comments")
    published = models.DateTimeField()

    class Meta:
        ordering = ['published']

python - Is it possible to sort elements in a ToManyField attribute us...

python django rest tastypie
Rectangle 27 1

I have a working prepend_urls .. you can take a look at the following example.

And the above methods is wrappered inside my resource model.

Error is likely to be caused due to some missing imports kindly try to import django.core.urlresolvers import resolve, from tastypie.utils import trailing_slash and try again. Let me know what happens when you do this.

Thanks. I needed to import django.conf.url. Now my only problem is the syntax for the url. I want it to show api/v1/friends/user/1 where 1 is the id of the user but I get an error message Invalid resource lookup data provided. How should my url be written.

def get_users(self,request):        self.method_check(request,['get'])        friends = []        for friend in Friends,objects.filter(Q(from_user=request.user)|Q(to_user=request.user)):             friends.append(friend)

There is a method to do this. You have mention that the user/ will be followed by a primary key in the regex that you have written in the prepend_urls method. Take a look at the following post. It has the primary key as you mentioned above stackoverflow.com/questions/12877437/

python - Django Tastypie prepend_urls error - Stack Overflow

python django api tastypie
Rectangle 27 0

When using Tastypie along with Django, you can set the Authentication attribute, look here for further reference.

django - backbone.js + tastypie: how to allow anyone to access API - S...

django backbone.js tastypie
Rectangle 27 0

Added in the field definition attribute=None instead of string naming, and then manually dehydrating field in full_dehydrate method or deleting this field from response depending on bundle.request.GET.get('param', None) value.

django-tastypie exclude field if request has filter - Stack Overflow

django tastypie
Rectangle 27 0

Patch is currently not supported on Heroku. It is not due to an nginx issue, but rather due to an issue in the routing layer. It is something Heroku is currently working on, but there is no ETA on it being available. Additionally you do not have the ability to add custom headers as these are controlled for you.

I tried to create this support ticket with Heroku, but their support system replied with "We're sorry, but something went wrong." So I'll post it here. Heroku support, HTTP PATCH requests are working in my local development instance but failing on my Heroku staging instance. Can you confirm that Heroku can or cannot support HTTP PATCH requests? I found this Stack Overflow (SO) question from April: stackoverflow.com/questions/10069871/

which suggests that this is a limitation of Heroku's routing layer. I have found no mention of it in the Heroku documentation. The SO question also suggests that custom header won't work with Heroku, but I have used them with no issue.

http - Heroku and Django with 405 error - Stack Overflow

django http heroku tastypie http-status-code-405
Rectangle 27 0

Ok. This is a Django error. I'm not sure, try to use related_name in the django model.

class ModelB(models.Model):
# Some fields
a = models.ForeignKey(ModelA, related_name='b_list')

Remove the related_name from the resource and the attribute name must change from 'a_set' to 'b_list'

class ResourceA(ModelResource):
b_list = fields.ToManyField('app.api.ResourceB', 'b_list', null=True)

Adding an item to a one_to_many relationship in django-tastypie only w...

django tastypie
Rectangle 27 0

from tastypie.validation import Validation

class MyValidation(Validation):

    def is_valid(self, bundle, request=None):
        errors = {}
        #if this dict is empty validation passes. 

        my_foo = foo.objects.filter(id=1)
        if not len(my_foo) == 0: #if object exists      
            foo[0].foo = 'bar'    #so existing object updated
            errors['status'] = 'object updated'  #this will be returned in the api response

        return errors 

    #so errors is empty if object does not exist and validation passes. Otherwise object
    #updated and response notifies you of this

class FooResource(ModelResource):
    class Meta:
        queryset = Foo.objects.all() # "id" = models.AutoField(primary_key=True)
        validation = MyValidation()

django - Convert POST to PUT with Tastypie - Stack Overflow

django tastypie
Rectangle 27 0

you're sending a $.POST request with jquery, yet you're trying to change the type to a GET. Use .ajax if you want to add custom options to the ajax request.

php - 401 UNAUTHORIZED error with jquery get method with Tastypie api ...

php jquery ajax django tastypie
Rectangle 27 0

A Resource is 'just' a python class so you could simply create a base resource and inherit it with only the queryset and resource_name Meta attributes defined.

You could probably automate naming too by fiddling with the Resource class's __new__ method or create a custom classmethod, but I'm not sure the effort will gain you much.

Registering the classes to the api can be automated in numerous ways, of which one could be:

for name, obj in inspect.getmembers(sys.modules['resources']):
    if inspect.isclass(obj):  # might want to add a few exclusions
        v1_api.register(obj())

where 'resources' is the name of the module containing resources, but this is kind of implicit..

Thanks, that makes sense. If I wanted to generate the Resource classes as well with their custom querysets and names I am thinking of using something like: rclass = type(cls.__name__+'Resource', (ModelResource,), {'Meta': type('Meta', (object,), {'queryset': cls.objects.all(), 'resource_name' : cls.__name__})})

python - Dynamically create Resources for multiple django models in ta...

python django tastypie
Rectangle 27 0

got it. the problem was in my json that was incomplete. i had a foreign key to my user resource that i didn't add. here is the solution:

{
    "product": "\/api\/reservation\/product\/12\/",
    "id": "7",
    "reserv_finish": "2013-01-06T15:26:15+00:00",
    "resource_uri": "\/api\/reservation\/reservation\/7\/",
    "penalty": false,
    "reserv_date_start": "2013-01-06T15:26:15+00:00",
    "user": "\/api\/reservation\/auth\/user\/1\/"
}
class ReservationResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')
    product = fields.ForeignKey(ProductResource, 'product')
    class Meta:
        queryset = Reservation.objects.all()
        resource_name = 'reservation'
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
public JSONObject encodeJsonObject(Reservation reservation){
    JSONObject obj=new JSONObject();
    obj.put("id",String.valueOf(reservation.getId()));  
    obj.put("product","/api/reservation/product/"+reservation.getProduct().getId()+"/");      
    obj.put("reserv_date_start",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+00:00'").format(reservation.getReserv_date_start()));
    obj.put("reserv_finish",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+00:00'").format(reservation.getReserv_finish()));        
    obj.put("resource_uri", "/api/reservation/reservation/"+reservation.getId()+"/");
    obj.put("user", "/api/reservation/auth/user/1/"); //not dynamic yet
    obj.put("penalty",reservation.isPenalty());
    return obj;
}

Create Resource on Django Tastypie with a Java POST request but gettin...

java django json rest tastypie
Rectangle 27 0

The fields defined in the meta attributes aren't enough to have the additional values returned. They need to be defined as additional fields in the resource:

distance = fields.CharField(attribute="distance", default=0, readonly=True)

This value can be filled by defining dehydrate_distance method inside the resource

def dehydrate_distance(self, bundle):
    # your code here

or by adding some additional elements to queryset in resources meta like so:

queryset = YourModel.objects.extra(select={'distance': 'SELECT foo FROM bar'})

Tastypie itself appends a field called resource_uri that isn't actually present in the queryset, looking at the source code of tastypie's resources might be helpful for you too.

That works! Thanks so much for that, it's exactly what I wanted! The value is actually be filled in by the .distance() geodjango function, so I just had to add that field definition. Once again, thanks!

Django TastyPie Geo Distance Lookups - Stack Overflow

django distance tastypie geo
Rectangle 27 0

Seems like tasty doesn't allow you to filter by virtual field, when the field attribute is represented by lambda.

You can make it work with some modifications:

class PostCategory(models.Model):
    post = models.ForeignKey(Post, related_name='categories')
    category = models.ForeignKey(Category)


class PostResource(ModelResource):
    user = fields.ToOneField(ProfileResource, 'user', full=True)
    categories = fields.ToManyField(PostCategoryResource, 'categories', full=True)

    class Meta:
        queryset = Post.objects.all()
        resource_name = 'post'
        filtering = {
            # filter by user
            'user': ALL_WITH_RELATIONS,

            #filter by category id
            'categories': ALL_WITH_RELATIONS,
            'category': ALL,
            'id': ['exact'],
        }

django - Tastypie ManyToMany filter - Stack Overflow

django tastypie