w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Return results from multiple models with Django REST Framework
It looks pretty close to me. I haven't used ViewSets in DRF personally, but I think if you change your code to this you should get somewhere (sorry - not tested either of these): class TimelineViewSet(viewsets.ModelViewSet): """ API endpoint that lists all tweet/article objects in rev-chrono. """ def list(self, request): queryset = list(itertools.chain(Tweet.objects.all(), Article.objects.all())) serializer = TimelineSerializer(queryset, many=True) return Response(serializer.data) If you're not wedded to using a ViewSet then a generics.ListAPIView would be a little simpler: class TimeLineList(generics.ListAPIView): serializer_class = TimeLineSerializer def get_queryset(self): return list(itertools.chain(Tweet.objects.all(), Arti

Categories : Python

Django REST framework + angular, autmatically appending backed errors to the DOM
When you want to write reusable code like this, your best choice is to use directives. You can create a directive named <email></email> and then inside the template, populate it with the input element and display the {{error}} next to it. There are several ways of getting the error into the directive template, but I'd suggest isolate scope and pass the data into the directive. This helps make directives more reusable. If you've done things correctly then your backend 'Django REST' shouldn't have anything to do with this front-end functionality for the directive. All you need to do is change the data inside the controller and it will automatically change the data in the directive. So it gives a good level of abstraction as well.

Categories : Angularjs

Django filter, paginate and annotate paginated results
OK, got it. I was selecting wrong table. So I changed .extra() and it's only COUNTing per page now: result = filter_search.qs.extra( select={ 'sub_count': 'SELECT COUNT(*) FROM report_subscribers WHERE report_subscribers.report_id = reports.id AND report_subscribers.report_id IN %s ' % "(%s)" % ",".join([str(r.id) for r in paged_reports.object_list]) } ) But now I can't sort by sub_count since I don't have all values. Well, perhaps there's no any other way of doing it without counting all or actually storing counts in a database

Categories : Python

Sending a jQuery Request to Django REST Framework Results in no found JSON object error
It turns out that turning the data sent into an actual string will make the JSON readable by the framework. According to the jQuery documentation this should happen either way, but it seems to have broken this specific data object lay out? This solves my problem, but I'm not sure what's wrong.

Categories : Jquery

Plug in django-allauth as endpoint in django-rest-framework
While I'm not quite sure how to use allauth and rest-fremework together, allauth does not offer such an endpoint. Suggestion: make your own that does a variation of the following: Call allauth.socialaccount.providers.facebook.views.fb_complete_login(None, socialtoken) where socialtoken is as created in login_by_token. That performs (a few functions deeper) a django.contrib.auth.login, possibly creating the acct. After that, for use on mobile devices, it might be possible to the the auth (not FB) token: get the user data (from session?), and call rest_framework.authtoken.views.obtain_auth_token Notes: 1. This offers no way to resolve email conflicts or connect social/local accts. 2. I haven't tried it - please post code if you can get it working.

Categories : Python

How to use TokenAuthentication for API in django-rest-framework
"how can I send the token with post request to my api" From the docs... For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b "at api side how can I verify if token is valid and belongs to the correct user?" You don't need to do anything, just access request.user to return the authenticated user - REST framework will deal with returning a '401 Unauthorized' response to any incorrect authentication.

Categories : Python

Django REST Framework API call using IOS.
When you use 'curl' and use the '-u myuser:mypass' you are sending the username and password in the HTTP Authorization header. I'm not sure how to do this in IOS specifically, but I would try doing a POST request with a url like: http://username:password@example.com/

Categories : IOS

django rest Framework authentications
Django rest framerwork supports many auth options. You can use Basic Auth if you want. If you want to use the token you will need to set an http header with the correct token for your user. From the docs you need to set it as (replace 99... with yours) Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

Categories : Python

Django Rest Framework global timestamp
If you add a DateTimeField to your model using the auto_now option you can order by that (decending) and limit to the first result to find the time of the latest update. A RetrieveAPIView in which you override get_object to return the last updated Item together with a serialiser that just exposes the DateTimeField should give you everything you need.

Categories : Django

django-rest-framework and custom routes
The part of the Django Rest Framework docs you're looking for is that on filtering against the URL. The basic idea is that you override get_queryset to return a filtered QuerySet matching parameters you define in your URL conf. The Django ORM field lookups you'll need are year, month and day, which start here in the QuerySet API reference. I hope that helps.

Categories : Django

AttributeError with Django REST Framework and MongoEngine
Finally got the solution. I needed to explicitly set many=False to make it work. So this works fine: from core.models import * from core.serializers import * tiger = Lady(firstname='Tiger', lastname="Lily") serial = LadySerializer(tiger, many=False) serial.data and yields: {'firstname': u'Tiger', 'lastname': u'Lily'} You can find some additional information regarding this problem here. The interesting part for this case is the following post: Version 2.2 starts the deprecation of the implicit iteration behavior. At the moment you'll need to explicitly specify many=False to force the behavior to not iterate over __iter__ style objects. By 2.4 the default value will switch from None to False. Hope this helps....

Categories : Python

django-rest-framework different fields for serialization
You could override to_native in your serializer subclass to strip the unwanted fields in your case. Something like: def to_native(self, obj): as_native = super(MySerializer, self).to_native(obj) # Remove image_url and image fields if Text role. if as_native["role"] == "Text": as_native.pop('image_url', None) as_native.pop('image', None) return as_native I hope that helps.

Categories : Django

Django Rest Framework - PUT to (many=True) PrimaryKeyRelatedField()
You need to set traditional to true so jquery will encode the params that contains arrays in a way that django will understand: $.ajax({ url:'<MY MODELVIEWSET>/<ID>', type:'PUT', traditional: true, data:{field1:'xyz', field2:[1,2,3]} }) See here for the difference between default and traditional encoding.

Categories : Django

django-rest-framework document API in OPTIONS
The generic views already include parameter descriptions in response the OPTIONS requests. For example, after completing the tutorial, you should be able to make OPTIONS requests and inspect the available actions. Make sure to set the --user option to an existing user/password, or you'll only have ready-only access and won't get the actions part of the response. bash: curl -X OPTIONS --user amy:amy -v http://127.0.0.1:8000/snippets/ -H 'Accept: application/json; indent=4'; echo * About to connect() to 127.0.0.1 port 8000 (#0) * Trying 127.0.0.1... connected * Server auth using Basic with user 'amy' > OPTIONS /snippets/ HTTP/1.1 > Authorization: Basic YW15OmFteQ== > User-Agent: curl/7.22.0 (x86_64-apple-darwin11.2.0) libcurl/7.22.0 OpenSSL/1.0.0e zlib/1.2.5 libidn/1.22 >

Categories : Django

Make BooleanField required in Django Rest Framework
There was an issue with Boolean fields and the required argument. Should now be fixed in master. See this issue: https://github.com/tomchristie/django-rest-framework/issues/1004

Categories : Django

How to pass django rest framework response to html?
Have you added TemplateHTMLRenderer in your settings? http://www.django-rest-framework.org/api-guide/renderers/#setting-the-renderers

Categories : Python

Django REST Framework HyperlinkedModelSerializer write operations
I think the HyperlinkedModelSerializer is reasonably documented here: http://django-rest-framework.org/api-guide/serializers#hyperlinkedmodelserializer ...may not have been when you last searched. Disclaimer: I am not a programmer or a rest_framework expert I could be on the totally wrong path here, but I feel a bit like the two things you are linking are different URIs - i.e. different resources in the www - and should probably be treated as such (unless you really don't need to separate the two things in the back-end). I don't mean that you should force a crappy experience on the consumer of your to-be-beautifully-RESTful API. I think you may be better off creating a function/method that can receive the data you are after in one call and then it can manage the object manipulation se

Categories : Python

How can I define a list field in django rest framework?
One way to deal with arrays for a non ORM-based object is to override the to_native and from_native methods. In your case: class TagsField(serializers.WritableField): def from_native(self, data): if isinstance(data, list): return Tags(data) else: msg = self.error_messages['invalid'] raise ValidationError(msg) def to_native(self, obj): return obj.tags If you had an ORM-based object you would like to look at the SlugRelatedField with the many = True attribute. From Django Rest Framework version 3.0 you can also use ListField http://www.django-rest-framework.org/api-guide/fields/#listfield

Categories : Django

Django REST Framework partial updates with depth
This was originally answered in the question, but I feel it deserves a decent explanation. In Django REST Framework 3, the process of saving nested data has been made considerably more clear. Now you can override update on the serializer and manipulate the validated_data, updating your model objects manually. This is specifically documented now, but the implementation is typically very specific to the situation. Original answer (in the question) by user2708386 Short answer is yes, it's possible. The problem was that I still needed to override the .save() method on my model to also save the related User object. class Users(models.Model): user = models.OneToOneField(User) foo = models.CharField() baz = models.CharField() yin = models.CharField() yang = models.

Categories : Python

model field named url and django rest framework url
It may be considered poor form (I am by no means a pro programmer or rest_framework expert), but I believe you can add extra context to the serialized output: http://django-rest-framework.org/api-guide/serializers.html#specifying-fields-explicitly class AccountSerializer(serializers.ModelSerializer): url = serializers.CharField(source='get_absolute_url', read_only=True) groups = serializers.PrimaryKeyRelatedField(many=True) class Meta: model = Account Extra fields can correspond to any property or callable on the model. So in the above the field 'get_absolute_url' must be in the 'Account' model. In your case (I think) you could do this: class ModelSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.Field(source='owner.username') ur

Categories : Django

Retrieving a Foreign Key value with django-rest-framework serializers
Just use a related field without setting many=True. Note that also because you want the output named category_name, but the actual field is category, you need to use the source argument on the serializer field. The following should give you the output you need... class ItemSerializer(serializers.ModelSerializer): category_name = serializers.RelatedField(source='category', read_only=True) class Meta: model = Item fields = ('id', 'name', 'category_name')

Categories : Django

Limit items per page in Django REST Framework
You need to set PAGINATE_BY as doc states: PAGINATE_BY: The default page size to use for pagination. If set to None, pagination is disabled by default PAGINATE_BY_PARAM is for users to override the default size. So if you are afraid of its misuse just don't enable it. PAGINATE_BY_PARAM: The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If set to None, clients may not override the default page size.

Categories : Django

Django REST framework object level permissions
I have done this in the past using a custom permission and overridden has_object_permission like the following: from rest_framework import permissions class MyUserPermissions(permissions.BasePermission): """ Handles permissions for users. The basic rules are - owner may GET, PUT, POST, DELETE - nobody else can access """ def has_object_permission(self, request, view, obj): # check if user is owner return request.user == obj You can do some more detailed things such as deny specific request types (for instance to allow a GET requests for all users): class MyUserPermissions(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Allow get requests for all if request.method == 'GET':

Categories : Python

Django-rest-framework serializer makes a lot of queries
select_related will work as expected with serializers. Make sure you're setting that in the 'queryset' attribute on the view if you're using the generic views. Using select_related inside 'get_queryset' will work too. Otherwise the only thing I can suggest is trying to narrow the issue down with some more debugging. If you still believe there's an issue and have a minimal example that'll replicate it then raise the issue as a ticket, or take the discussion to the mailing list.

Categories : Django

How I can allow a user to modify only their data in django rest framework?
You want to adapt the example from the tutorial about associating snippets with users. Keep your get_queryset implementation and then set the user field to the request user in pre_save.

Categories : Django

How to add permissions in Django Rest Framework for specific requests
By default permissions are unrestricted. In your settings.py you can specify a different set of defaults to where users have to be authenticated and have the correct Django model permission. You will need to specify a model attribute on your view class for the DjangoModelPermissions to take effect. # settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissions' ) } # views.py class DocumentList(APIView): model = Document ... The DjangoModelPermissions permission map can be found in the source. GET, OPTIONS and HEAD don't require a permission but since we specified IsAuthenticated we're still requiring that POST maps to add PUT and PATCH map to change DELE

Categories : Django

Django REST Framework - Serializing optional fields
The serializers are deliberately designed to use a fixed set of fields so you wouldn't easily be able to optionally drop out one of the keys. You could use a SerializerMethodField to either return the field value or None if the field doesn't exist, or you could not use serializers at all and simply write a view that returns the response directly. Update for REST framework 3.0 serializer.fields can be modified on an instantiated serializer. When dynamic serializer classes are required I'd probably suggest altering the fields in a custom Serializer.__init__() method.

Categories : Python

How to query by unique attribute with Django-Rest-Framework (Many To Many)
Try this: filter(clients__hostname=clients) Take a look at https://docs.djangoproject.com/en/1.5/topics/db/queries/#spanning-multi-valued-relationships

Categories : Python

Return Create Object ID Django Rest Framework
What does your serializer look like? Does it have the 'id' in the fields to be included? http://django-rest-framework.org/api-guide/serializers.html#specifying-which-fields-should-be-included The serializer decides what the object returned looks like in the API

Categories : Python

How can one customize Django Rest Framework serializers output?
Create a custom serializer field and implement to_native so that it returns the list you want. If you use the source="*" technique then something like this might work: class CustomField(Field): def to_native(self, obj): return obj.macAddresses.all() I hope that helps.

Categories : Python

Getting mongoengine and django rest framework to play nice
Django REST Framework is intended to work well with Django's models. As MongoEngine is not a replacement for Django's Models, you will need to define a few more functions for it to play nice with Django Rest framework. If you need a framework build for MongoEngine, you might want to take a look at django-tastypie-mongoengine instead. If you prefer to use Django REST Framework it's perfectly feasible though. Your BlogList class is actually a View, not a Serializer. First, define a serializer class: from rest_framework import serializers from .models import Blog class BlogSerializer(serializers.Serializer): post_id = serializers.IntegerField() title = serializers.CharField(max_length=144) date_created = serializers.DateTimeField(required=False) body = serializers.CharFiel

Categories : Django

Design history tracking database using django-rest-framework
Found this question which is very similar to mine. How can I apply a filter to a nested resource in Django REST framework? And I solved my problem by using the SerializerMethodField

Categories : Django

Django Rest Framework bulk updates inserting instead of updating
The obvious thing that pops out is that you're not passing object instances to your serializer. (Thus it will create new instances rather than update.) See the docs on dealing with multiple objects in serializers where you'll see your QuerySet passed in.

Categories : Django

Django-rest-framework timezone aware renderers/parsers
I had the same problem and solved it by adding new type of field: class DateTimeTzAwareField(serializers.DateTimeField): def to_native(self, value): value = timezone.localtime(value) return super(DateTimeTzAwareField, self).to_native(value) and now you can use it in ModelSerializer: class XSerializer(serializers.ModelSerializer): start = DateTimeTzAwareField() end = DateTimeTzAwareField() class Meta: model = XModel fields = ( 'id', 'start', 'end', )

Categories : Django

Adding field that isn't in model to serializer in Django REST framework
What you can do is to overwrite the pre_save or create function and take out the commenter_pw from the data fields that are sent (not sure, but you can probably take it out form request.POST or after you have serialized it), so the framework should not rise the error. Plus, if you have additional logic you can implement it there before saving it (such as the one for checking if the user have to be created or what).

Categories : Python

Django REST Framework: serializing a model from callable to primary key
You could use a SerializerMethodField to return a value, for example: class FooSerializer(serializers.ModelSerializer): def getBarId(self, foo): return foo.get_bar().id barid = serializers.SerializerMethodField('getBarId')

Categories : Django

Dynamically modifying serializer fields in Django Rest Framework
Note that you are setting serializer_class not to a class, but to an instance of the class. You either need to set dropfields as an attribute on the class, (just like it does for fields in the documented example you link to) or you need to look at overriding the get_serializer method of the viewset (docs).

Categories : Python

Django Rest Framework does not deserialize data passed as raw JSON
I guess that's the way it is when you are using Browsable API then. I think you shouldn't use Browsable API to test JSON request, use curl instead: curl -v -H "Content-type: application/json" -X POST -d '{"foo": 1, "bar": 1}' http://127.0.0.1:8000/api/something/ Hope it helps.

Categories : Django

Change model-object at PUT and update before GET in django-rest-framework
I kinda found a solution, but it feels somewhat dirty.. In my serializers restore_object I put code like this: new_values = instance.update_counters() for k, v in new_values.items(): self.data[k] = v and in my models update_counters() function, I am returning a dict of what I changed..

Categories : Django

Django REST Framework: What's really the difference between validate_ and validate?
Raising a ValidationError inside validate_<foo>() will result in a field error. {'foo': ['Not a fooish value.']} Raising a ValidationError inside validate() will result in non-field error. {'non_field_errors': ['Foo and bar are not compatible.']} So why are there both options? Partly because of the above, and partly because the serializer API mirrors Django's form API where possible. There's some differences where needed, but the validate and validate_<foo> style is similar. In my case, which option is correct to use? You judgement call, based on which error message is more appropriate.

Categories : Validation



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.