Menu
  • HOME
  • TAGS

How to get URL Id inside serializers create method?

python,django,django-rest-framework

Inside your create method you should be able to access the arguments passed to the view rendering your endpoint at self.context['view'].kwargs.get('member_id') ...

DRF Update Existing Objects

django,django-rest-framework

In your view, you need to provide the following: lookup_field -> Most probably the ID of the record you want to update lookup_url_kwarg -> The kwarg in url you want to compare to id of object You need to define a new url in your urls.py file. This will carry...

django rest post return 405 error code

django,django-rest-framework

POST are supposed to be for creation purpose. If you want to update with a ViewSet you'll need to PUT or PATCH (partial update) instead. Edit: For more about this, here's some explanation on the HTTP methods used for REST API: http://restful-api-design.readthedocs.org/en/latest/methods.html This is also described in the DRF documentation...

Django rest framework generic view for multiple models

django-rest-framework

A solution would be overriding the get_serializer_class method of the ViewSet. The model field in the view will be fine as you override it in the url, as you said, what I would do is build the serializer class on the fly. class GenericViewSet(generics.ListAPIView): queryset = model.objects.all() def get_serializer_class(self): class...

How to get Request.User in Django-Rest-Framework serializer?

django,django-rest-framework

You cannot access the request.user directly. You need to access the request object, and then fetch the user attribute. Like this: user = self.context['request'].user Or to be more safe, user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user More on extra context can be read...

I don't understand how Django-Rest-Framework serializers work

django,django-rest-framework

There is too much black box magic which confuses the configuration instructions (in my opinion). If there is something in the documentation that you think can be improved, feel free to submit a pull request with an update. If it seems reasonable, it will probably be merged and show...

User registration endpoint in Django Rest Framework

django,django-rest-framework

Forgive me to digress a little, but I can't help but wonder use could have gotten away with far less code, than you have if you had created a serializer and used a class-based view. Besides, if you had just created email as EmailField of serializer it would have automatically...

Django-rest post returns get

django-rest-framework

Got it. Move from http to https wasn't reflected in the URL.

Django REST error returning a list of objects

python,django,rest,django-rest-framework

You can just return a dictionary with the data you need. class NewGameView(GenericAPIView): serializer_class=NewGameRequestSerializer def post(self, request, format=None): serializer = NewGameRequestSerializer(data=request.DATA) if serializer.is_valid(): req=serializer.save() mygamedata=...; # request game data objects data = {'game_name': mygame_object.name} return Response(data,status=status.HTTP_201_CREATED) ...

DjangoRestFramework ModelSerializer: field-level validation is not working

django,django-models,error-handling,django-rest-framework,django-serializer

Field-level validation is called before serializer-level validation. So model User having username as unique=True, the field-level validation will raise exception because of username being already present. DRF's UniqueValidator does this work of raising exception when a field is not unique. As per DRF source code, class UniqueValidator: """ Validator that...

Django Rest framework replacing my currently authenticated user with AnonymousUser whenever I call it via ajax?

javascript,python,django,django-rest-framework

The body of the 403 error should include a friendly message explaining what the issue is, I think in this case you will find that the message is complaining about a lack of CSRF token. Note that this only applies to js. I can hit the url from a browser...

Django Rest Framework adding 2 numbers

python,django,django-models,django-rest-framework

Since you have a model and you want to list, retrieve and create instances, I would recommend you to use Viewsets. So, it would be sth like: from rest_framework import viewsets from rest_framework.decorators import detail_route class NumViewSet(viewsets.ModelViewSet): queryset = Num.objects.all() serializer_class = NumSerializer # This method will return the sum...

django-rest-framework how to make model serializer fields required

python,angularjs,django,django-rest-framework

You need to override the field specifically and add your own validator. You can read here for more detail http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly. This is the example code. def required(value): if value is None: raise serializers.ValidationError('This field is required') class GameRecord(serializers.ModelSerializer): score = IntegerField(validators=[required]) class Meta: model = Game ...

Django REST serializer and extra attributes from custom model fields

python,django,rest,django-rest-framework

Question 1: I want to be able to access the test1-info attribute just like i would be able to access the name1-max_length attribute. Yes, you can access your info attribute by ModelField.model_field.info. you can see the example below. Question 2 for your final goal: I think you can customize your...

Django Rest Framework - Non Field Error Custom Message

python,django,django-models,django-rest-framework

When you have unique_together set on a model, the serializer will automatically generate a UniqueTogetherValidator that is used to check their uniqueness. You can confirm this by looking at the output of the serializer, and introspecting what Django REST framework automatically generates: print(repr(DeviceContractSerializer())) You can then alter the validators that...

Content-Range configuration for Django Rest Pagination

dojo,pagination,django-rest-framework,http-content-range

If you are talking about providing Content-Range in the response, I mentioned in an answer to another SO question (which I believe may also have originated from your team?) that there is one alternative to this header: if your response format is an object (not just an array of items),...

django - “Incorrect type. Expected pk value, received str” error

django,serialization,foreign-keys,django-rest-framework

The issue is that you are passing the name of the related Destination object into the serializer, instead of passing the pk/id of the Destination object. So Django REST framework is seeing this and complaining, because it can't resolve LA into an object. It sounds like you may actually be...

DjangoRestFramework - registering a user: difference between UserSerializer.save() and User.objects.create_user()?

django,django-views,django-rest-framework,user-registration

Neither of those is perfect. But View A looks promising. View A is a good start, but it is incomplete solution. Because User creation is not simply User.save, but rather you have to call User.create_user method. View B is the correct way to create user by calling User.create_user, however, the...

Using .update with nested Serializer to post Image

django,rest,django-models,django-rest-framework,imagefield

As noted in the docs, .update() doesn't call the model .save() or fire the post_save/pre_save signals for each matched model. It almost directly translates into a SQL UPDATE statement. https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on...

Django test RequestFactory vs Client

django,unit-testing,django-views,django-rest-framework,django-testing

RequestFactory and Client have some very different use-cases. To put it in a single sentence: RequestFactory returns a request, while Client returns a response. The RequestFactory does what it says - it's a factory to create request objects. Nothing more, nothing less. The Client is used to fake a complete...

Django Rest Framework: empty request.data

python,django,django-rest-framework,python-requests

You need to send the payload as a serialized json object. import json import requests payload = {"foo":"bar"} headers = {'Content-type': 'application/json'} r = requests.put("https://.../myPk/", data=json.dumps(payload), headers=headers) Otherwise what happens is that DRF will actually complain about: *** ParseError: JSON parse error - No JSON object could be decoded You...

Django rest framework sending a string with single quotes back instead of JSON with double quotes

django,python-3.x,django-rest-framework

It appears that leasee = models.CharField(max_length=2000) is a charfield. So Django is simply returning the string stored in this field. Also it is not storing valid JSON string neither because JSON only allows double quote. {'compare': {'uniqueVsChic': '56'}, 'profession': {'hairStylist':True, 'esthetician': True, 'permanentMakeup': True}, 'name':'dfasdfasdf', 'contact':{'facebook': True,'text': True}} looks like...

Using Django REST Framework API for data model with composite key

python,django,rest,django-rest-framework

The problem lies into the fact that the DefaultRouter uses the id lookup_field of your model for getting the object you want: For example this works: GET localhost/api/v1/stocksusa/1 In order to provide extra parameters you need to hand-craft the urls like this: url(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})/(?P<code>\w+)$', StocksUsaViewSet.as_view(), name='stocks_detail' ), The year month day...

How to work with django-rest-framework in the templates

json,django,django-templates,django-rest-framework

model.py: class Day(models.Model): date = models.DateField(default=date.today) def get_todo_list(self): return self.day_todo_set.order_by('-id')[:5] class ToDo(models.Model): date = models.ForeignKey(Day, related_name="day_todo_set") name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) In serializers.py class ToDoSerializer(serializers.ModelSerializer): class Meta: model = ToDo field = ('id', 'date', 'name', 'very_important', 'finished') class...

How to use PrimaryKeyRelatedField to update categories on a many-to-many relationship

python,django,django-rest-framework

For anyone else having this issue I found a solution that allows PrimaryKeyRelatedField to be read/writeable. Just add queryset categories = serializers.PrimaryKeyRelatedField(many=True, queryset=Category.objects.all()) It will still filter on the correct relationship which is a bit confusing....

Django Rest Framework - how to create custom error messages for all ModelSerializer fields?

django,validation,error-handling,django-rest-framework,django-serializer

In order to replace unique or regex error messages you should change message member of corresponding validator object. This could be done using separate mixin class: from django.core.validators import RegexValidator from rest_framework.validators import UniqueValidator from django.utils.translation import ugettext_lazy as _ class SetCustomErrorMessagesMixin: """ Replaces built-in validator messages with messages, defined...

JWT authentication doesn't work for custom controller in Django

django,authentication,django-rest-framework,json-web-token

I started doing this in comments and it was too long. Generally, you haven't really provided enough code to assist properly, but here's my crack anyway. It's not obvious which version/implementation of Django JWT you're using (there are a few), how you're authorising your views, or whether your calculations.py file...

How to test registration on django rest framework

django,django-rest-framework,django-allauth,django-rest-auth

You need to use CURL to interact with the API. Something like this $ curl -X POST -d 'username=admin&password=1234' http://localhost:8000/register/ OR go through this link it might help you....

Django REST tutorial DEBUG=FALSE error

python,django,django-rest-framework

This error: File "/tutorial/tutorial/urls.py", line 9, in <module> url(r'^admin/', include(snippets.urls)), NameError: name 'snippets' is not defined occurs because snippets.urls has to be quoted. See the example here: urlpatterns = [ url(r'^', include('snippets.urls')), ] As shown here, you could write something like this: from django.contrib import admin urlpatterns = [ url(r'^polls/',...

Django Rest Framework PUT request on unique model field

django,django-models,django-rest-framework,django-serializer

As per the comments implementing the put method closer to the reference implementation in the docs should fix the issue. def put(self, request, pk, format=None): device = self.get_object(pk) serializer = DeviceSerializer(device, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Saving instances has a bit more information on creating, updating...

Django Rest Framework's serializer.is_valid() raising validation errors even though required=false

django,django-rest-framework

Try adding allow_blank=True in your serializer's name and email fields. name = CharField(read_only=False, required=False, allow_null=True, allow_blank=True) email = CharField(read_only=False, required=False, allow_null=True, allow_blank=True) From http://www.django-rest-framework.org/api-guide/fields/#charfield max_length - Validates that the input contains no more than this number of characters. min_length - Validates that the input contains no fewer than this number...

Creating multiple model instances in DRF3

django,django-models,django-views,django-rest-framework

As of Django REST framework 3.1, it is not possible to submit multiple values using form data. This is because there is no standardized way of sending lists of data with associations, which is required for handling a ListSerializer. There are plans to implement HTML JSON forms support, which would...

Django Rest Framework Pagination Overriding

django,pagination,django-rest-framework

Using None as the value has the same effect as not setting the paginate_by attribute at all. Have a look at the code of DRF. You'll have to set an explicit value there for it to have effect. As long as we're on the topic, though, the 'PAGINATE_BY' global setting...

Email field required django.contrib.auth

django,django-rest-framework,django-rest-auth

I want to register an user in django-rest-auth, if all username, password and email fields are provided. The correct way to require a field on a serializer in Django REST framework is to set required=True when initializing the field, or using the extra_kwargs parameter to set it on automatically...

Django update without required fields

django,api,rest,django-rest-framework

UPDATE is possible via 2 requests: PUT and PATCH PUT updates all the fields of the object on which the operation is to be performed. It basically iterates over all the fields and updates them one by one. Thus, if a required field is not found in the supplied data,...

Django REST Framework API Management

django,api,django-rest-framework

Following @sthzg's comment, I made a registration-based approach which works out pretty well. registration.py: def register_api(cls): try: # check for membership api = API.objects.get( module=cls.__class__.__module__, name=cls.__class__.__name__, ) # update api except API.DoesNotExist: # register api api = API( module=cls.__class__.__module__, name=cls.__class__.__name__, ) api.save() models.py: class API(models.Model): module = models.CharField(max_length=256) name =...

django rest framework - using detail_route and detail_list

python,django,routing,django-rest-framework

Your code is almost correct, you're just the right signature on the register method: def register(self, request): This is the correct signature according to the documentation. Additionally the tests suggest that it's not possible to pass an additional parameter for routing, and that pk will always be passed for a...

Database first Django models

python,django,django-models,django-rest-framework,django-serializer

You can use the information on this link. python manage.py inspectdb > models.py https://docs.djangoproject.com/en/1.7/howto/legacy-databases/ It depends on your database, but I've worked with it and is good....

Django Rest Framework TypeError at / __init__() got multiple values for keyword argument 'read_only'

python,django,django-models,django-rest-framework,django-serializer

The field HyperlinkedIdentityField is always read-only, that is why it doesn't support read_only argument. Allowed arguments: view_name lookup_field lookup_url_kwarg format ...

Error: [ngModel:datefmt] Expected `2015-05-29T19:06:16.693209Z` to be a date - Angular

javascript,angularjs,django,django-rest-framework

This must be happening with angular 1.3+. 1.3+ on wards ng-model for date/time input needs to be a valid date object, string representation of date is no longer allowed. You need to convert string to date object ($scope.created_time = new Date(dateString)) and bind it to the ng-model. If you follow...

Serializer needs to include more info in a GET while accepting primitives in a POST

django,django-rest-framework

To get a read-only representation of the employee, you can add a SerializerMethodField. This will leave your employee field intact for POST and PUT requests and add a serialized representation at employee_data. class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee class ShiftSerializer(serializers.ModelSerializer): confirmed_location = LocationSerializer(required=False) # this will look for a...

Django REST Framework - Custom Permissions not Evaluating

django,django-rest-framework

The method name is has_permission not has_permissions (no s) ;)

DjangoRestFramework Class Serializers missing “Meta” attribute?

django,python-2.7,django-rest-framework

meta does not equal Meta. Python is case-sensitive.

Django REST Exceptions

django,rest,django-rest-framework

The Django REST framework provides several built in exceptions, which are mostly subclasses of DRF's APIException. You can raise exceptions in your view like you normally would in Python: from rest_framework.exceptions import APIException def my_view(request): raise APIException("There was a problem!") You could also create your own custom exception by inheriting...

Django Rest Framework Form

django,django-rest-framework

I managed to return an html snippet for a form using the following method on my viewset: class CustomViewSet(ModelViewSet): @list_route() def form(self, request, *args, **kwargs): serializer = self.get_serializer() renderer = HTMLFormRenderer() form_html = renderer.render(serializer.data, renderer_context={ 'template': 'rest_framework/api_form.html', 'request': request }) return HttpResponse(form_html) I needed to use a vanilla django HttpResponse,...

How can I register a single view (not a viewset) on my router?

python,django,django-rest-framework

Routers work with a ViewSet and aren't designed for normal views, but that doesn't mean that you cannot use them with a normal view. Normally they are used with models (and a ModelViewSet), but they can be used without them using the GenericViewSet (if you would normally use a GenericAPIView)...

how to use django restframework as a backend for mobile apps

django,django-rest-framework

I think the easiest way to think about it, is that Django Rest Framework will (normally) return or process JSON data, rather than an HTML page / HTML form data. Your models stay the same. If you use Django's ModelForms then DRF's ModelSerialzers are very similar in use. Likewise, using...

How to deserialize nested objects with Django Rest Framework

json,django,django-rest-framework

You can pass additional arguments on .save. So I think you just need to pass the newly created book instance to the serializer, e.g. def create(validated_data): chapters = validated_data.pop('chapters') book = Book(**validated_data) book.save() serializer = ChapterSerializer(data=chapters, many=True) if serializer.is_valid(raise_exception=True): chapters = serializer.save(book=book) ...

Django Rest Framework Pagination Settings - Content-Range

django,pagination,django-rest-framework

1. Including Link Header in response: To include a Link header in your response, you need to create a custom pagination serializer class, This should subclass pagination.BasePagination and override the get_paginated_response(self, data) method. Example (taken from docs): Suppose we want to replace the default pagination output style with a modified...

Update user profile and user in one request

django,python-2.7,serialization,django-rest-framework,django-rest-auth

Disclaimer I was finally able to figure it out and I am only answering for future reference. I am not sure if this is best practice or the easiest way to accomplish the task. However, this is what I was able to come up with. I changed the view to...

ForeignKey ListField serialization on rest_framework with django-nonrel

django,mongodb,serialization,django-rest-framework,django-nonrel

The issue here is that you are passing a string (unicode type) to DRF but you are expecting DRF to turn it into a nested representation. Without anything extra, DRF is not possible to do this, as it's way out of the general scope that it tries to maintain. Django...

Django rest framework, JWT and request.session

django,session,session-variables,django-rest-framework,jwt

request.session is managed through Django's session framework which requires the use of session cookies and is what powers SessionAuthentication. JWT is completely separate from session authentication, and does not provide a way to store arbitrary data on the token....

DjangoRestFramework - How to get result from different serializers into one

python,django,django-rest-framework,django-serializer

Assuming you are on Django REST Framework v3.0+, I would suggest looking at the Django REST Framework Documentation on Serializer Relations. In addition, you will want to utilize ForeignKey.related_name on your models.ForeignKey fields. Models class Product(models.Model): title = models.CharField(max_length=255) short_description = models.TextField(blank=True,null=True) video_link = models.URLField(blank=True,null=True) price = models.IntegerField(db_index=True,blank=True,null=True) user =...

django rest framework field level validation in form

django,validation,field,django-rest-framework

The errors are not coming because DRF is running field validations initially. If those validations fail, the default errors are shown. As per the source code, the default error messages are stored in default_error_messages dictionary. Following are some code snippets: Field: class Field(object): default_error_messages = { 'required': _('This field is...

Some actions with object in UpdateAPIView when update

python,django,django-rest-framework

You can get it with self.get_object() Take a look at the source UpdateView, which you are overriding. You can use the same method to get the object: class UpdateModelMixin(object): """ Update a model instance. """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance,...

Django user login through api [duplicate]

django,security,django-rest-framework

Keep in mind using a Django form will only allow you to use SessionAuthentication under DRF - more notes here. Short of it is to use the Django LoginViews when creating login pages, and the notes on using CSRF tokens if you do use Session Auth with DRF. http://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication How...

Python / Django Rest Framework weird error happening only when using debugger

python,django,django-rest-framework

SOLUTION: First of all it seems to me that there is a bug with either pydevd or Django Rest Framework, that made my code work when in debugging mode and stoping in breakpoints (showed in the video). But I am not expert in Django / Python so it could be...

Django Rest Framework ModelSerialzer field doesn't respect required=False

django,django-rest-framework

I added read_only=True to the created_by field, now it's working fine. class CommentSerializer(ContentSerializer): created_by = UserSerializer(required=False, read_only=True) content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False) class Meta: model = Comment ...

Add a boolean field if a row exists in another table?

python,django,django-rest-framework,django-1.7

Piggybacking off of dydek's answer here. You overwrite your get_queryset in the Api View class PostList(generics.ListAPIView): ... def get_queryset(self): Post.objects.all().extra(select={ 'current_user_replies_count': 'SELECT COUNT(*) FROM <reply table> WHERE' + 'post_id=posts_post.id AND owner_id = %s' },select_params=(request.user.id,)) This will add 'current_user_replies_count' as a property to the Post objects in your queryset. ...

Django REST: Allow foreign key to be get_or_created() in POST/PUT

django-rest-framework

I think I may have found the right way to do this: Derive from serializers.CharField and override to_internal_value() to get_or_create(): class CityField(serializers.CharField): def to_internal_value(self, data): value = super(CityField, self).to_internal_value(data) return City.objects.get_or_create(name=value)[0] ...

Django doesn't parse a custom http accept header

python,django,http,django-views,django-rest-framework

Try defining a custom renderer and setting the media_type attribute. from rest_framework.renderers import JSONRenderer class MyRenderer(JSONRenderer): media_type = 'application/vdn.name.v1+json' Then enable your renderer (see the docs for more info) REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'path.to.MyRenderer', 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) } ...

Django Rest Framework image upload and get image

django-rest-framework

Django REST framework provides an ImageField that can handle the uploading of images using Django's file upload handlers. So you might be interested in learning how it is done in Django first: Need a minimal Django file upload example

daterange on a django-filter

python,django,django-rest-framework,django-filters

I can't speak to the Django REST Framework part of your question, but I hope I can lend some insight to the django-filter part! If you use a DateRangeFilter, the result would be a dropdown with the options "any date", "today", "past 7 days", "this month" and "this year". If...

Stuck with nested serializer using Django Rest Framework and default user

django,api,rest,django-rest-framework,serializer

By default DRF will look at an attribute on the User model named after the serializer's field (member here). However the related name is profile. This can be worked around by passing the source="profile" to your MemberProfileSerializer....

customising a model field for serialization

django-models,django-rest-framework

First you can split the education field value by using split. Then you can serialize it accordingly. class CustomModel: def __init__(self, year,course,college,description): self.year = year self.course = course self.description = description self.college = college class CustomSerializer(NonNullSerializer): year = serializers.IntegerField() course = serializers.CharField() description = serializers.CharField() college = serializers.CharField() Add this...

django rest_framework viewset has no route

django,django-rest-framework

I should have used the ModelViewSet: class ListingViewSet(viewsets.ModelViewSet): ^^^^^ Thanks to xordoquy for pointing it out in the issue I opened....

Attribute error when attempting to get a value for field

python,django,django-rest-framework

The issue is that you are passing a queryset into your serializer without setting the many flag. The error is telling you that the serializer is trying to access queryset.user when it should be accessing visitor.user, so you need to tell the serializer that there are multiple objects (instead of...

Django REST framwork 3.1 - PUT-as-create mixin class, custom lookup_field

python,json,django-rest-framework

My mistake was from poor understanding from making correct use of the kwargs. I corrected my code in the question post. Thanks!...

Why `create()` method of django rest framework serializer return a value?

python-2.7,django-rest-framework,serializer

It returns the created instance so that the created user can be used anywhere if need be. There are often use cases where you might need the user or any other generic saved instance somewhere in your code. So upon saving always, the saved instance is returned so that the...

Django Rest Framework + React + Reflux: Can't GET new objects

django,reactjs,django-rest-framework,refluxjs

The problem ended up being with the Cache-Control header of the response having a max-age=600. Changing that to max-age=0 solved the issue. In this situation, it doesn't make much sense to provide a cached response, so this I added this to my serializer's ViewSet: def finalize_response(self, request, *args, **kwargs): response...

django rest framework - adding to views.obtain_auth_token

view,override,django-rest-framework,http-token-authentication

You can find the relevant view here: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/authtoken/views.py#L21 Assuming you've created some sort of User serializer already, you can basically take the user instance there and shove it into your UserSerializer. then add it to the response, something like the below. ... user_serializer = UserSerializer(user) return Response({'token': token.key, 'user': user_serializer.data})...

Python/Django - datetime dropping the time portion when updating serializer data

python,django,django-rest-framework

The problem you are seeing is that you are modifying the serializer data from the outside, which doesn't actually propagate to the data used internally. So even though you are changing the start_datetime and end_datetime fields, internally DRF still sees the datetime objects that only contain the date. You have...

Is there even any need to use the django rest framework [closed]

django,django-rest-framework

Of course you don't need DRF. After all, it's just an app that has been written in Python for Django. This essentially means that you can re-create anything you want. However, after a certain point, you'll find you're just duplicating DRF and would probably be better off using it if...

Django rest frame getting values from all tables where the PK is referenced as FK

python,django,django-rest-framework

I think that you might need to include many=true and change the source to the be related_name in the StudioProfileSerializer: class StudioProfileSerializer(serializers.ModelSerializer): services = StudioServicesSerializer(many = true, source = "services") pic_of_studio = StudioPicSerializer(many = true, source = "pic_of_studio") class Meta: model = StudioProfile fields = ( 'address_1', 'address_2','services','pic_of_studio' ) ...

Django - Dojo/Dgrid - how to manage LARGE data sets

mysql,django,dojo,django-rest-framework,dgrid

I don't know how to answer this on the layer between DRF and the database, but as discussed in other SO questions like this one, DRF allows you to limit the amount of data sent with requests via page or offset/limit parameters. Based on the phrasing of your question, it...

Add a non-model field on a ModelSerializer in DRF 3

python,django,django-rest-framework

class TestSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='vote_detail') non_field = serializers.serializers.SerializerMethodField() # no corresponding model property. class Meta: model = vote_model fields = ("url", "non_field") def create(self, validated_data): print(direction=validated_data['non_field']) http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield or go through this link...

Django Rest Framework Ordering on a SerializerMethodField

django,django-rest-framework

This is not possible using the default OrderingFilter, because the ordering is implemented on the database side. This is for efficiency reasons, as manually sorting the results can be incredibly slow and means breaking from a standard QuerySet. By keeping everything as a QuerySet, you benefit from the built-in filtering...

Django Rest Framework - how to get Http header information in urls.py

python,django,django-views,django-rest-framework,django-urls

You can't access request on urls.py, see: How Django processes a request You can configure versioning on django-rest-framework and get version on request object like: class SampleView(APIView): def post(self, request, format=None): if request.version == '1': return Response(status=status.HTTP_410_GONE) Or use URLPathVersioning approach....

Python Django REST API test

python,django,testing,django-rest-framework

Thanks guys for your input. I found out that I should be using APITestCase instead of TestCase for DRF. I have Implemented both of your answers into my test script and I have got a working test script that looks like this: from customer.models import Customer, CustomerStatus from customer.views import...

Django REST Framework : update() based on query string parameter

python,django,django-rest-framework

Assuming you want to use the same url for listing and for retrieving the details of the entity, discriminating on the presence of the url parameter job-def-id, here is a crazy idea: class JobDefinitionsAllInOneView(mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = JobDefinitions.objects.all() serializer_class = JobDefinitionsSerializer def get_object(self): job_def_id = self.request.query_params.get('job-def-id', None)...

Is it possible to restrict url access from application only in Dajngo REST

angularjs,django,rest,django-rest-framework

You can't rely on the URL to distinguish between the two cases. You could have your application provide information in the headers of the request, which a browser would not know, but someone writing their own application could mimic your technique.

django rest framework validation & refreshing data

django,validation,django-rest-framework

Instead of adding field-level validation, add this check to your object-level validation because you require access to multiple fields. Even the DRF docs define this: Object-level validation To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes...

Django Rest Framework without authentication + GET only

python,django,rest,django-rest-framework

If you have a login, but you don't have SSL, then your users are vulnerable to packet sniffing of credentials on many wifi and ethernet networks. Such a vulnerability can be trivially exploited with the Firesheep firefox plugin. Due to users' habit of reusing passwords, you could end up compromising...

Updating a nested many-to-many

python,django,django-rest-framework

You might try to subclass ModelSerializer instead of HyperlinkedModelSerializer and then supply the queryset argument for the PrimaryKeyRelatedField: categories = serializers.PrimaryKeyRelatedField(many=True, queryset=Categories.objects.all()) ...

DjangoRestFramework - How to pass a serializer form to the frontend?

django,angularjs,django-models,django-forms,django-rest-framework

Well here are a few things I think we might need to point out. Django forms are normally what you would use to create a new user, with a post request just like you are trying to do through DRF. Now you can do this through DRF, but thats not...

ManyToMany Through Field Serialization

python,json,django,serialization,django-rest-framework

By changing the OrderSerializer items field to be an OrderItemField I was able to get back to root Order by using self.root.instance and then using that in conjuction with the value, which is an Item instance, build a query to find the OrderItem object to get the quantity. Then I...

Is it correct to use a ViewSet and the APIView mixins on the same view in Django REST Framework?

django,python-2.7,django-rest-framework

In all versions of Django REST framework, the generic API views and ViewSet classes are distinctly separate, but the mixins can be shared across them. This is because the viewsets actually inherit from the generic classes in the first place. As stated before, you can use the generic mixins though...

Django Rest + Jinja2: ValueError: dictionary update sequence element #0 has length 0; 2 is required

python,django,rest,django-rest-framework,jinja2

I was able to fix the problem by writing my own renderer, here a JinjaTemplateRenderer Although this is not really working in the end, many problems with it, I will just go back to using normal class based views instead of the REST framework as it does not satisfy my...

Django REST Framework's APIClient sends None as 'None'

python,django,django-rest-framework

The problem here is that the APIClient is sending data to the view as form-data by default, which doesn't have a concept of None or null, so it is converted to the unicode string None. The good news is that Django REST framework will coerce a blank string to None...

When are create and update called in djangorestframework serializer?

python,django,django-rest-framework

You really must split things between the views and the serializer. Serializers The Serializer is a standalone object. It is used for converting a Django model (or any kind of python datastructure, actually) into a serialized form, and the other way around. You may use it as such, wherever you...

Assign JSON field to model variable in django

django,django-models,django-rest-framework

If you are using djangorestframework you will need to override to_representation function in your serializer http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior should be something like this def to_representation(self, obj) serialized_data = super(SerializerClassName, self).to_representation(obj) serialized_data["2or4"] = serialized_data["twoOrFour"] //Remove the old field name del serialized_data["twoOrFour"] return serialized_data This code should work where...