Questions tagged [django-rest-framework]
Django REST framework is a powerful and flexible toolkit for building RESTful Web APIs. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.
31,805
questions
315
votes
9
answers
174k
views
Django rest framework, use different serializers in the same ModelViewSet
I would like to provide two different serializers and yet be able to benefit from all the facilities of ModelViewSet:
When viewing a list of objects, I would like each object to have an url which ...
231
votes
13
answers
337k
views
How can I enable CORS on Django REST Framework
How can I enable CORS on my Django REST Framework?
the reference doesn't help much, it says that I can do by a middleware, but how can I do that?
222
votes
4
answers
66k
views
How to disable admin-style browsable interface of django-rest-framework?
I am using django-rest-framework. It provides an awesome Django admin style browsable self-documenting API. But anyone can visit those pages and use the interface to add data (POST). How can I disable ...
222
votes
11
answers
190k
views
Django REST Framework: adding additional field to ModelSerializer
I want to serialize a model, but want to include an additional field that requires doing some database lookups on the model instance to be serialized:
class FooSerializer(serializers.ModelSerializer):
...
220
votes
15
answers
159k
views
How to get Request.User in Django-Rest-Framework serializer?
I've tried something like this, it does not work.
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
def save(self):
user = self.context['request....
208
votes
5
answers
184k
views
What's the appropriate HTTP status code to return if a user tries logging in with an incorrect username / password, but correct format?
A similar question is posted here: What's an appropriate HTTP status code to return by a REST API service for a validation failure?
The answer in the thread above states that "For instance if the ...
200
votes
37
answers
230k
views
django.db.migrations.exceptions.InconsistentMigrationHistory
When I run python manage.py migrate on my Django project, I get the following error:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)...
194
votes
4
answers
118k
views
How do I include related model fields using Django Rest Framework?
Let's say that we have the following model:
class Classroom(models.Model):
room_number = [...]
class Teacher(models.Model):
name = [...]
tenure = [...]
classroom = models.ForeignKey(...
192
votes
13
answers
91k
views
Disable a method in a ViewSet, django-rest-framework
ViewSets have automatic methods to list, retrieve, create, update, delete, ...
I would like to disable some of those, and the solution I came up with is probably not a good one, since OPTIONS still ...
185
votes
1
answer
53k
views
Django REST framework: non-model serializer
I am beginner in Django REST framework and need your advice. I am developing a web service. The service has to provide REST interface to other services. The REST interface, which I need to implement, ...
171
votes
17
answers
146k
views
Django Rest Framework remove csrf
I know that there are answers regarding Django Rest Framework, but I couldn't find a solution to my problem.
I have an application which has authentication and some functionality.
I added a new app ...
168
votes
16
answers
91k
views
Django: TemplateDoesNotExist (rest_framework/api.html)
In my view function, I'd like to return a json object (data1) and some text/html (form). Is this possible?
MY code
@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
if ...
164
votes
22
answers
227k
views
Django Rest Framework - Authentication credentials were not provided
I'm developing an API using Django Rest Framework. I'm trying to list or create an "Order" object, but when i'm trying to access the console gives me this error:
{"detail": "Authentication ...
160
votes
5
answers
124k
views
How to change field name in Django REST Framework
I am trying to change Model field name in DRF Serializer like alias in SQL. I have tried different methods but cannot succeed.
models.py
class Park(models.Model):
name = models.CharField(...
160
votes
7
answers
39k
views
What are the differences between django-tastypie and djangorestframework? [closed]
Why would you use one over the other, for exposing an API for your Django app?
http://pypi.python.org/pypi/djangorestframework/
http://pypi.python.org/pypi/django-tastypie
159
votes
22
answers
101k
views
Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"
I am building a project in Django Rest Framework where users can login to view their wine cellar.
My ModelViewSets were working just fine and all of a sudden I get this frustrating error:
Could not ...
149
votes
24
answers
263k
views
Django Rest Framework File Upload
I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this:
class ProductList(APIView):
authentication_classes = (authentication.TokenAuthentication,)
def ...
148
votes
8
answers
236k
views
Retrieving a Foreign Key value with django-rest-framework serializers
I'm using the django rest framework to create an API.
I have the following models:
class Category(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
...
148
votes
11
answers
163k
views
Django rest framework serializing many to many field
How do I serialize a many-to-many field into list of something, and return them through rest framework? In my example below, I try to return the post together with a list of tags associated with it.
...
148
votes
2
answers
69k
views
When to use Serializer's create() and ModelViewset's perform_create()
I want to clarify the given documentation of Django-rest-framework regarding the creation of a model object. So far I have found that there are 3 approaches on how to handle such events.
The ...
145
votes
4
answers
60k
views
How to serialize Model @property with ModelSerializer?
I'm trying to serialize a model containing a property field that I also want to serialize.
models.py:
class MyModel(models.Model):
name = models.CharField(max_length=100)
slug = models....
143
votes
10
answers
85k
views
Django Rest Framework: Dynamically return subset of fields
Problem
As recommended in the blogpost Best Practices for Designing a Pragmatic RESTful API, I would like to add a fields query parameter to a Django Rest Framework based API which enables the user to ...
143
votes
4
answers
41k
views
Include intermediary (through model) in responses in Django Rest Framework
I have a question about dealing with m2m / through models and their presentation in django rest framework. Let's take a classic example:
models.py:
from django.db import models
class Member(models....
142
votes
6
answers
210k
views
Django REST Framework custom fields validation
I am trying to create custom validation for a model, to check that its start_date is before its end_date and it is proving near impossible.
Stuff I've tried:
built-in Django validators: none check ...
141
votes
12
answers
71k
views
Token Authentication for RESTful API: should the token be periodically changed?
I'm building a RESTful API with Django and django-rest-framework.
As authentication mechanism we have chosen "Token Authentication" and I have already implemented it following Django-REST-Framework's ...
133
votes
8
answers
84k
views
Python Django Rest Framework UnorderedObjectListWarning
I upgraded from Django 1.10.4 to 1.11.1 and all of a sudden I'm getting a ton of these messages when I run my tests:
lib/python3.5/site-packages/rest_framework/pagination.py:208:
...
131
votes
9
answers
125k
views
Django Rest Framework with ChoiceField
I have a few fields in my user model that are choice fields and am trying to figure out how to best implement that into Django Rest Framework.
Below is some simplified code to show what I'm doing.
# ...
129
votes
32
answers
338k
views
Django Rest Framework -- no module named rest_framework
I've installed django rest framework using pip install djangorestframework yet I still get this error when I run "python3 manage.py sycndb":
ImportError: No module named 'rest_framework'
I'm using ...
121
votes
6
answers
37k
views
TemplateDoesNotExist - Django Error
I'm using Django Rest Framework. and I keep getting an error
Exception Type: TemplateDoesNotExist
Exception Value: rest_framework/api.html
I dont know how I'm going wrong. This is the first time I'...
121
votes
8
answers
129k
views
How to add custom field in ModelSerializer?
I created a ModelSerializer and want to add a custom field which is not part of my model.
I found a description to add extra fields here and I tried the following:
customField = CharField(source='...
120
votes
26
answers
211k
views
SocketException: OS Error: Connection refused, errno = 111 in flutter using django backend
I m building a flutter app with django rest-framework. The registration api is working fine in Postman but after some successful registration from the flutter app it is showing the above error. The ...
120
votes
12
answers
73k
views
Django rest framework nested self-referential objects
I have model that looks like this:
class Category(models.Model):
parentCategory = models.ForeignKey('self', blank=True, null=True, related_name='subcategories')
name = models.CharField(...
120
votes
6
answers
49k
views
How do you filter a nested serializer in Django Rest Framework?
In Django Rest Framework, how do you filter a serializer when it's nested in another serializer?
My filters are imposed in the DRF viewsets, but when you call a serializer from inside another ...
117
votes
6
answers
175k
views
Write only, read only fields in django rest framework
I have models like this:
class ModelA(models.Model):
name = models.CharField()
class ModelB(models.Model):
f1 = models.CharField()
model_a = models.ForeignKey(ModelA)
Serializers:
...
115
votes
8
answers
103k
views
Pass request context to serializer from Viewset in Django Rest Framework
I have a case where the values for a serializer field depend on the identity of the currently logged in user. I have seen how to add the user to the context when initializing a serializer, but I am ...
115
votes
12
answers
58k
views
Django or Django Rest Framework [closed]
I have made a certain app in Django, and I know that Django Rest Framework is used for building APIs. However, when I started to read about Django Rest Framework on their website, I noticed that each ...
110
votes
11
answers
118k
views
RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am building an application with Django Rest Framework and AngularJs. I am using Django-rest-auth for my authentication purposes, although, I have not been able to set it up. Anyway, I am trying to ...
110
votes
7
answers
152k
views
Django Rest Framework partial update
I'm trying to implement partial_update with Django Rest Framework but I need some clarification because I'm stuck.
Why do we need to specify partial=True?
In my understanding, we could easily update ...
109
votes
8
answers
111k
views
Pass extra arguments to Serializer Class in Django Rest Framework
I want to pass some arguments to DRF Serializer class from Viewset, so for I have tried this:
class OneZeroSerializer(rest_serializer.ModelSerializer):
def __init__(self, *args, **kwargs):
...
109
votes
20
answers
202k
views
CSRF Failed: CSRF token missing or incorrect
I'm using Django 1.7 and django-rest-framework.
I made an API that returns me some JSON data putting this in my settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework....
106
votes
1
answer
69k
views
Django REST framework serializer without a model
I'm working on a couple endpoints which aggregate data. One of the endpoints will for example return an array of objects, each object corresponding with a day, and it'll have the number of comments, ...
105
votes
9
answers
76k
views
How do I create multiple model instances with Django Rest Framework?
I would like to save and update multiple instances using the Django Rest Framework with one API call. For example, let's say I have a "Classroom" model that can have multiple "Teachers". If I wanted ...
105
votes
13
answers
59k
views
DRF: Simple foreign key assignment with nested serializers?
With Django REST Framework, a standard ModelSerializer will allow ForeignKey model relationships to be assigned or changed by POSTing an ID as an Integer.
What's the simplest way to get this behavior ...
104
votes
11
answers
116k
views
How to register users in Django REST framework?
I'm coding a REST API with Django REST framework. The API will be the backend of a social mobile app. After following the tutorial, I can serialise all my models and I am able to create new resources ...
96
votes
10
answers
84k
views
How Can I Disable Authentication in Django REST Framework
I'm working on a store site, where every user is going to be anonymous (well, until it's time to pay at least), and I'm trying to use Django REST Framework to serve the product API, but it keeps ...
95
votes
11
answers
53k
views
Django REST Framework - Separate permissions per methods
I am writing an API using Django REST Framework and I am wondering if can specify permissions per method when using class based views.
Reading the documentation I see that is quite easy to do if you ...
95
votes
4
answers
32k
views
What is the benefit of using a HyperlinkedModelSerializer in DRF?
In reference to this link, I've seen plenty of examples of using a HyperlinkedModelSerializer in Django Rest Framework. It says:
The HyperlinkedModelSerializer class is similar to the ...
94
votes
7
answers
241k
views
"Post Image data using POSTMAN"
I am trying to POST data to my API. I have a model with an image field where:
image = models.ImageField()
I have an image on my local box, which I am trying to send. Am I sending it correctly?
{
...
94
votes
1
answer
36k
views
Difference between views and viewsets?
Maybe relevant: What does django rest framework mean trade offs between view vs viewsets?
What is the difference between views and viewsets? And what about router and urlpatterns?
93
votes
10
answers
56k
views
How to set current user to user field in Django Rest Framework?
I have the following code working perfectly. I can create a Post object from DRF panel by selecting an image and a user. However I want DRF to populate the user field by the currently logged in user.
...