FAQ Database Discussion Community


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

django,validation,error-handling,django-rest-framework,django-serializer
This is my serializers.py (I want to create a serializer for the built-in User model): from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', ) I'm aware that Django Rest Framework has it's own field validators, because when I...

django rest framework field level validation in form

django,validation,field,django-rest-framework
I am using ModelViewSet and TemplateHTMLRenderer to use the form and process 'post' method. When I tried render a field error, the error rendered [u'This field may not be blank.']. How can I make it render the simple message 'This...'? in html, <form action="." method="post" id="myform"> <input name="first_name" type="text"> <ul>...

Using .update with nested Serializer to post Image

django,rest,django-models,django-rest-framework,imagefield
I have an ImageField. When I update it with the .update command, it does not properly save. It validates, returns a successful save, and says it is good. However, the image is never saved (I don't see it in my /media like I do my other pictures), and when it...

How to get URL Id inside serializers create method?

python,django,django-rest-framework
I have the following URL: url(r'^member/(?P<member_id>\d+_([\w-]+){22})/join/?$', views.ActivityJoinView.as_view(), name='member_join'), Within my DRF serializer create method I need to get access to member_id. I have tried this: class JoinListSerializer(serializers.ModelSerializer): class Meta: model = Join fields = ("id", ) def create(self, validated_data): print(self.context['request'].query_params) I've also tried validated_data.get('member_id', None) But still get bank/none! How...

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

javascript,python,django,django-rest-framework
I'm trying to add a few interactive things the to Django admin page via a simple RESTful api and Javascript. Should be simple, but I'm facing a weird issue where every single one of my requests from javascript is returning a 403 authorization error. Note that this only applies to...

Attribute error when attempting to get a value for field

python,django,django-rest-framework
I'm working with the django rest framework and the serializer I'm trying to use is creating errors. I'm trying to do something like https://gist.github.com/anonymous/7463dce5b0bfcf9b6767 but I still get the error. the models are class Visitor(models.Model): user = models.OneToOneField(User) check_ins = models.IntegerField(default=0) @classmethod def create(cls, username, email, password): user = User.objects.create_user(username,...

Django Rest Framework Form

django,django-rest-framework
What I want to do: Django Rest Framework comes with a renderer for returning a HTML form from a serializer[1]. After poring through the docs and then through the code, I still cannot figure out how to get it to render a blank form. What I think the problem might...

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

python,django,django-rest-framework
The Django Rest Framework has a PrimaryKeyRelatedField which lists ID's on my many-to-many relationship with categories... class CatalogueItemsSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='catalogue_item_detail') name = serializers.CharField(min_length=2, max_length=60) categories = serializers.PrimaryKeyRelatedField(many=True, read_only=True) I would like to override the create() get a lot of posted ID's (traditionally DRF wants me to send URL's) on...

DjangoRestFramework not validating required = True

python,django,django-rest-framework
I am facing a very weird issue today. Here is my serializer class. class Connectivity(serializers.Serializer): device_type = serializers.CharField(max_length=100,required=True) device_name = serializers.CharField(max_length=100,required=True) class Connections(serializers.Serializer): device_name = serializers.CharField(max_length=100,required=True) connectivity = Connectivity(required = True, many = True) class Topologyserializer(serializers.Serializer): name = serializers.CharField(max_length=100,required=True, \...

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
I'm learning Django REST Framework (http://tomchristie.github.io/rest-framework-2-docs/, we're still on version 2.4). Is it correct to define a class like this, for instance: class UserView(generics.RetrieveUpdateDestroyAPIView, generics.ListCreateAPIView, viewsets.GenericViewSet): # ... rest of class In other words, is it correct or possible to use *ViewSet and *APIView mixins/classes together, or are they intended...

django rest_framework viewset has no route

django,django-rest-framework
I started a new django application with django rest_framework. One thing is odd though - when I try the example from the quickstart it works fine: I get a route at http://localhost:8000/users/ that I can query. But it doesn't work with my own app which is as minimal as it...

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

django,django-rest-framework
Using django rest framework 3.1.1, I have the following serializer: class CommentSerializer(ContentSerializer): created_by = UserSerializer(required=False) content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False) class Meta: model = Comment While the content field respects the required=False parameter, but created_by does not, which in result, gives me a list of "This field is required" validation errors...

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

django,serialization,foreign-keys,django-rest-framework
I my django-rest-framework I have the following models: Basically every ride has one final destination and can have multiple middle destinations. models.py: class Destination(models.Model): name=models.CharField(max_length=30) class Ride(models.Model): driver = models.ForeignKey('auth.User', related_name='rides_as_driver') destination=models.ForeignKey(Destination, related_name='rides_as_final_destination') leaving_time=models.TimeField() num_of_spots=models.IntegerField() passengers=models.ManyToManyField('auth.User',...

JWT authentication doesn't work for custom controller in Django

django,authentication,django-rest-framework,json-web-token
I am using the Django Rest Framework in my Python app, and am using JSON Web Token Authentication (DRF JWT) for the api authentication. My problem comes when I am building a custom controller. I pointed a specific URL to a function in my calculations.py file that I created. Following...

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

django,django-rest-framework
I wanted to build a backend which resembled a RESTful architecture, and I came across something called the Django REST Framework, which talked about serialization, response (JSONResponse()) and user authentication to build a Web API. However, all these functions are already available in Django 1.8 (serialization, JSONResponse(), user authentication), so...

Django REST Framework API Management

django,api,django-rest-framework
I'm trying to make certain attributes related to my APIs configurable (these are unrelated to DRF attributes), it's more of meta data that I would like to utilize for my own application. For this purpose, I'm creating an app I'm calling apimanager for the sole purpose of API management. The...

How to deserialize nested objects with Django Rest Framework

json,django,django-rest-framework
Say I have Django models like this: class Book(models.Model): title = models.CharField(max_length=150) author = models.CharField(max_length=150) class Chapter(models.Model): book = models.ForeignKey(Book, related_name='chapters') title = models.CharField(max_length=150) page_num = models.IntegerField() and Django Rest Framework classes like this: class ChapterSerializer(serializers.ModelSerializer): class Meta: model = Chapter fields = ('id', 'title', 'page_num') class BookSerializer(serializers.ModelSerializer): chapters =...

Django REST serializer and extra attributes from custom model fields

python,django,rest,django-rest-framework
How can i pass extra attributes from my custom model field to the serializer? For example i have this custom model field RsTestField which has an extra attribute "info" which is True or False: class RsTestField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "CharField" def __init__(self, info=False, *args, **kwargs): self.info =...

Django Rest Framework Ordering on a SerializerMethodField

django,django-rest-framework
I have a Forum Topic model that I want to order on a computed SerializerMethodField, such as vote_count. Here are a very simplified Model, Serializer and ViewSet to show the issue: # models.py class Topic(models.Model): """ An individual discussion post in the forum """ title = models.CharField(max_length=60) def vote_count(self): """...

Django doesn't parse a custom http accept header

python,django,http,django-views,django-rest-framework
Is there any way to allow Django app to accept the custom accept header like "application/vdn.name.v1+json"? I keep getting a response like this Could not satisfy the request Accept header. I am using Django Rest Framework as well...

When are create and update called in djangorestframework serializer?

python,django,django-rest-framework
I'm currently implementing djangorestframework for my app RESTful API. After playing around with it, I still do not clearly understand what .create(self, validated_data) and .update(self, validated_data) used for in the serializer. As I understand, CRUD only calls the 4 main methods in viewsets.ModelViewSet: create(), retrive(), update(), and destroy(). I also...

How to send multiple files using rest_framework.test.APITestCase

python,testing,django-rest-framework
I'm trying to send a couple of files to my backend: class AccountsImporterTestCase(APITestCase): def test(self): data = [open('accounts/importer/accounts.csv'), open('accounts/importer/apartments.csv')] response = self.client.post('/api/v1/accounts/import/', data, format='multipart') self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED) But I'm getting an error: Error Traceback (most recent call last): File "/vagrant/conjuntos/accounts/tests/cases.py", line 128, in test response = self.client.post('/api/v1/accounts/import/',...

Django REST Framework - Custom Permissions not Evaluating

django,django-rest-framework
I'm trying to set custom permissions on a class that extends viewsets.ModelViewSet and it appears that my permissions are not being evaluated. Here is my view: from rest_framework import viewsets from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated import models import serializers from permissions import IsAdminOrAuthenticatedReadOnly class KPIViewSet(viewsets.ModelViewSet): '''...

DjangoRestFramework Class Serializers missing “Meta” attribute?

django,python-2.7,django-rest-framework
I want to use DjangoRestframework in django app but i get error when call it? When call it , i give response me : Exception Type: AssertionError Exception Value: Class CrawlerSerializers missing "Meta" attribute But i written Meta Class in serializer class Please help me serializers.py file : from rest_framework...

Email field required django.contrib.auth

django,django-rest-framework,django-rest-auth
I want to register a user in django-rest-auth, if all username, password and email fields are provided. (I want to implement token authentication too to obtain a JSON response from the server.) The default email field in django.contrib.auth.User is optional. But I want to set the email filed as required...

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

python,django,django-rest-framework
In my tests, I send mock data of models that I've passed through the serializer. The serializer.data looks something like this { "field": None } However, the data that my API receives is formatted like { "field": "None" } which is a problem because I'm trying to specify a foreign...

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

django,python-3.x,django-rest-framework
I am sending JSON via POST to a view. The response I get back is only part JSON and the rest has changed from double quotes to single quotes. My question is how to I make sure that I am sending all this back as JSON in a get? As...

ForeignKey ListField serialization on rest_framework with django-nonrel

django,mongodb,serialization,django-rest-framework,django-nonrel
I have a class called Collection class Collection(models.Model): slug = models.CharField(max_length=32, primary_key=True) name = models.CharField(max_length=200) description = models.TextField() user = models.ForeignKey(User) videos = ListField(models.ForeignKey(Video)) pub_date = models.DateTimeField('date published') objects = MongoDBManager() with a videos property that is a ListField of Video object ForeignKeys. When I try to Serialize Collection object...

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

python,django,rest,django-rest-framework,jinja2
I am currently developing a Django website using the Jinja2 template engine using the django-jinja package. As the website will need a JSON api I thought of using the Django Rest Framework (DRF). Everything worked nicely before using DRF, using class based views that inherited from django's class based views...

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

javascript,angularjs,django,django-rest-framework
I'm working on angularapplication with Django with rest-framework.. The app receives it's info with json from the server.. One of the keys is created_time... The value of this field is format according to iso-8601, for example 2015-05-29T19:06:16.693209Z. In the client I have a field: <input type="time" ng-model="created_time"> But when the...

Django Rest Framework image upload and get image

django-rest-framework
I have a use case where an angular front end will need to submit image and Django Rest Framework API will need to save it to filesystem during image upload calls. During image download scenario the image will need also be served up from filesystem. If someone already figured out...

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

python,django,django-rest-framework
Is it possible to modify a ViewSet's update() function to update based on a query string parameter instead of a URL resource name or the request body? For example, I want trigger something like this: payload = {'field' : '2'} r = requests.put("http://127.0.0.1:9876/job-defs?job-def-id=2", data=payload) and have this update my field...

Django Rest Framework Pagination Overriding

django,pagination,django-rest-framework
I think I am establishing a global pagination setting and overriding it in a base viewset, but that does not seem to be happening. In my settings, I have: REST_FRAMEWORK = { 'PAGINATE_BY': 10 } but on my viewset I have class MyViewSet(viewsets.ReadOnlyModelViewSet): """ DRF endpoint. """ queryset = MyModel.objects.all()...

Some actions with object in UpdateAPIView when update

python,django,django-rest-framework
My code: class CarView(generics.UpdateAPIView): permission_classes = (IsAdminUser,) serializer_class = CarSerializer def get_queryset(self): return ... def update(self, request, *args, **kwargs): # some actions return super(CarView, self).update(request, *args, **kwargs) In update method I want to do some operations with updated object. How to do this?...

django rest post return 405 error code

django,django-rest-framework
I am using django with rest framework and I try to test POST on existing object but I keep getting 405. my ViewSet looks like this: class Agents(viewsets.ModelViewSet): serializer_class = serializer.AgentSerializer model = serializer_class.Meta.model .... and in the urls: router = routers.SimpleRouter() router.register(r'rest/agents', api_views.Agents, "Agent") ... urlpatterns += router.urls I...

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

python,django,django-rest-framework
How do add a non-model field on a ModelSerializer in DRF 3? i.e. add a field that does not exist on my actual model? class TestSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='vote_detail') non_field = serializers.CharField() # no corresponding model property. class Meta: model = vote_model fields = ("url", "non_field") def create(self, validated_data): print(direction=validated_data['non_field'])...

Django Rest Framework - Non Field Error Custom Message

python,django,django-models,django-rest-framework
I have looked at this question but that doesn't really tell me about non-field errors. My Model is: class DeviceContact(models.Model): created = models.DateTimeField(auto_now_add=True) contact_sid = models.CharField(max_length=75, db_index=True) contact_name = models.CharField(max_length=200) contact_email = models.CharField(max_length=250, db_index=True) contact_type = models.CharField(max_length=200, default='mobile') class Meta: unique_together = ("contact_sid", "contact_email", "contact_name") class...

django rest framework - understanding authentication and logging in

rest,authentication,login,django-rest-framework
I am a beginner to django rest framework (and to REST in general) and I have a server side which (for now) has a UserViewSet which allows to register new users and I can POST to the url from my android app just fine (I get 201 CREATED). I read...

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

python,django,django-rest-framework
With my parent model - StudioProfile, other models have a foreign key relationship to StudioProfile. How can I get all related table data when an API request is made to my StudioProfile serializer. Below are my models, views and serializers, class StudioProfile(models.Model): name = models.CharField(max_length = 120) address_1 = models.CharField(max_length...

How to test registration on django rest framework

django,django-rest-framework,django-allauth,django-rest-auth
I'm new to django rest framework. I'm following this tutorial to make a registration/login and using facebook authentication. I finish the tutorial everything looks fine. But I would like to try to register a user and try it also with facebook. But I don't know how to try. I know...

Include a nested element in Django Rest framework serializer

python,django,django-rest-framework
I'm trying to list all the images of a single Item in Django rest Framework serializer. In models : class Item(TimeStampedModel, AbsoluteUrlMixin, ObjectReviewsMixin): ... class ItemImage(models.Model): item = models.ForeignKey(Item, related_name='pictures') picture = models.ImageField(null=True, blank=True, upload_to="items") in the viewset : class ItemImageViewSet(viewsets.ModelViewSet): queryset = ItemImage.objects.all() serializer_class = ItemSerializer() in serializer :...

Django-rest post returns get

django-rest-framework
I built out an API with django-rest, tested it on a local machine, and pushed it to my PaaS. On my local machine a view associated with a post works perfectly. The live site throws an error. Decorator for view in question: @api_view(['POST']) Error: u'{"detail":"Method \"GET\" not allowed."}'. Python Request...

Django Rest Framework without authentication + GET only

python,django,rest,django-rest-framework
I am developing a back-end for a webpage using Django Rest Framework. The webpage will be public, and it will only fetch information from this service. Thus, I have to deploy both service and webpage. Since the webpage is public access (without any type of login) I can avoid having...

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

python,django,django-rest-framework
I am using Django REST Framework, specifically a ModelSerializer instance, to receive some date/time information, among other fields. The Django form which POSTs or PUTs to my view is using a single field for date, and separate fields for hour, minute, and am/pm. I wrote a function to deal with...

Django REST tutorial DEBUG=FALSE error

python,django,django-rest-framework
I'm trying to learn to use the django REST framework via the tutorial. I've gotten to the section "Testing our first attempt at a Web API". When I start the server, I get: System check identified no issues (0 silenced). June 15, 2015 - 00:34:49 Django version 1.8, using settings...

django rest framework validation & refreshing data

django,validation,django-rest-framework
I am trying to validate whether password1, password2 are matching not using object level validation because it is executed after all field level validations, but validate_field only accepts one value. How can I implement the following in rest framework? def validate_password2(self, data): print 'validating...' password1, password2 = data['password1'], data['password2'] if...

User registration endpoint in Django Rest Framework

django,django-rest-framework
I'm using Django rest framework. I've written the following view to register a new user to the system. @api_view(['POST']) @csrf_exempt @permission_classes((AllowAny, )) def create_user(request): email = request.DATA['email'] password = request.DATA['password'] try: user = User.objects.get(email=email) false = False return HttpResponse(json.dumps({ 'success': False, 'reason': 'User with this email already exists' }), content_type='application/json')...

Database first Django models

python,django,django-models,django-rest-framework,django-serializer
In ASP.NET there is entity framework or something called code first from database. Is there something similar for Django? I usually work with a pre-existing database that I need to create a backend (and subsequently a front end) for. Some of these RDBs have many tables and relations so manually...

Stuck with nested serializer using Django Rest Framework and default user

django,api,rest,django-rest-framework,serializer
The models and serializers are described in the pastebin: http://pastebin.com/ZxzxWY7V In my database I have a user which also has a member profile and a set of credentials attached to it. Now... when I run this as is and try to pull a user using the AuthUserModelSerializer I get the...

Django Rest Framework: empty request.data

python,django,django-rest-framework,python-requests
I have the following code for a view of DRF: from rest_framework import viewsets class MyViewSet(viewsets.ViewSet): def update(self, request, pk = None): print pk print request.data I call the URL via python-requests in the following way: import requests payload = {"foo":"bar"} headers = {'Content-type': 'application/json'} r = requests.put("https://.../myPk", data= payload,...

Django rest framework: override create() in ModelSerializer passing an extra parameter

python,django,django-rest-framework,overriding
I am looking for a way to properly ovverride the default .create() method of a ModelSerializer serializer in Django Rest Framework for dealing with an extra parameter. In my original Django model I have just overridden the default.save() method for managing an extra param. Now .save() can be called also...

Django test RequestFactory vs Client

django,unit-testing,django-views,django-rest-framework,django-testing
I am trying to decide whether I should use Django's Client or RequestFactory to test my views. I am creating my server using DjangoRESTFramework and it's really simple, so far: class SimpleModelList(generics.ListCreateAPIView): """ Retrieve list of all route_areas or create a new one. """ queryset = SimpleModel.objects.all() serializer_class = SimpleModelSerializer...

Name of view inside decorator_from_middleware class

python,django,django-rest-framework
While using this implementation for logging events by view I came across the need to get the name of the view. How do you do that ?

Django user login through api [duplicate]

django,security,django-rest-framework
This question is an exact duplicate of: django rest framework - understanding authentication and logging in 1 answer I want to create a login form for users to sign into a django site. The site is set up using django rest framework and I am considering having the login...

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

python,django,django-views,django-rest-framework,django-urls
I am making a Django-based API and here is my urls.py. from django.conf.urls import include, url api_version = "v1" urlpatterns = [ url(r'^v1/', include( "api."+ api_version +".urls", namespace=api_version )), ] What I want to do is to retrieve API version from http accept header. I tried to use django.http.HttpRequest module,...

django rest framework - using detail_route and detail_list

python,django,routing,django-rest-framework
In my code I have a viewset for the User. I want is to allow only Read operations (/users/42 and /users/) which the ReadOnlyModelViewSet does just fine. In addition, I want to have a /users/register URL that I can POST to in order to register a new User. class UserViewSet(viewsets.ReadOnlyModelViewSet):...

Rest Framework: HyperlinkedRelatedField, return multiple attributes?

django,django-rest-framework
Django Rest Framework's HyperlinkedRelatedField is used to serialize related fields like this: 'tracks': [ 'http://www.example.com/api/tracks/45/', 'http://www.example.com/api/tracks/46/', 'http://www.example.com/api/tracks/47/' ] I'm looking for a way to return multiple attributes, something like: 'tracks': [ {'id': 45, 'href': 'http://www.example.com/api/tracks/45/'}, {'id': 46, 'href': 'http://www.example.com/api/tracks/46/'}, {'id': 47, 'href': 'http://www.example.com/api/tracks/47/'} ] Is there a way to achieve...

Update user profile and user in one request

django,python-2.7,serialization,django-rest-framework,django-rest-auth
Thanks in advance for looking. The goal: In short: Update django user object and custom user profile object only if there is a change from a single view. The problem: For starters, this is my first time trying to do anything like this, so it may be something really simple...

Using Django REST Framework API for data model with composite key

python,django,rest,django-rest-framework
How do you use Django Rest Framework to create an API when the data model has a composite key consisting of two fields? Background: I am trying to make a REST api for a data model (sample data row below- first two entries make the composite key). I am able...

Updating a nested many-to-many

python,django,django-rest-framework
I have a Serializer that looks like this: { "id": 97, "categories": [ 23, 18 ], }, Where categories is a many-to-many on my model. I don't want a nested view just IDs so I used a PrimaryKeyRelatedField. So this works only if I have read_only=True which I don't want....

Django Rest Framework adding 2 numbers

python,django,django-models,django-rest-framework
I am new to Django Rest framework.For learning I am creating a class Num as from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item...

Django rest framework, JWT and request.session

django,session,session-variables,django-rest-framework,jwt
I use Django rest framework with JWT for authentication and everything works perfectly BUT... I need to save an information about the user in a session var at login and I really don't know where I can do the request.session['mydata'] = plop I tried : def jwt_response_payload_handler(token, user=None, request=None): serializedUser...

Django Rest Framework PUT request on unique model field

django,django-models,django-rest-framework,django-serializer
I have the following model class Owner(models.Model): user = models.OneToOneField(User, default=1, editable=True) phone = models.CharField(max_length=40, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) city = models.CharField(max_length=255, null=True, blank=True) state = USStateField(null=True, blank=True) zip = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Device(CreationModificationMixin): _STATUSES = (...

Content-Range configuration for Django Rest Pagination

dojo,pagination,django-rest-framework,http-content-range
I need to send a content-range header to a dojo/dgrid request: I cannot find any examples of HOW to do this. I'm not exactly sure where this setting goes (Content-Range: items 0-9/*). I have been given a great linkheaderpagination example on this question: Django Rest Framework Pagination Settings - Content-Range...

DjangoRestFramework - How to get result from different serializers into one

python,django,django-rest-framework,django-serializer
I've 4-5 models as follow:- 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 = models.ForeignKey(User) @staticmethod def get_product_details(product,category=None,image=None,comment=None,rating=None): product_detail = { 'id' : product.id, 'title' : product.title, 'short_description' : product.short_description, 'video_link' :...

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

python-2.7,django-rest-framework,serializer
I don't understand why the create() method in DRF serializer has to return a value. E.g.: class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username', 'email', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user Would not be sufficient save User...

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

json,django,django-templates,django-rest-framework
Please bear with me. I am just learning django-rest-framework. And I really can't seem to grab it. model: class Day(models.Model): date = models.DateField(default=date.today) class ToDo(models.Model): date = models.ForeignKey(Day) name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) normal view: def home(request): days = Day.objects.all() return render(request, 'test.html', { 'days':days })...

Django update without required fields

django,api,rest,django-rest-framework
I'm trying to execute an update through my API. When I push an update, I do not have all the required fields, because I'm only trying to update the ones that have changed. I get a 400 "This field is required." error. I know the field is required, but I'm...

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

django,django-rest-framework
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.user'] title = self.validated_data['title'] article = self.validated_data['article'] I need a way of being able to access request.user from my Serializer class. ...

customising a model field for serialization

django-models,django-rest-framework
I am doing a project on django. I have a model EmployeeProfile with several fields along with a field education with following data - (institute, year, course, description). in model i am storing data in form of a deliminated field. e.g. a sample value for education - " XYZ colllege...

Django rest framework generic view for multiple models

django-rest-framework
Is there a way of creating a generic view to be used by several different models? I have many models in my project and do not want to have to create a view and serializer for each of them. Assume this is a simple solution but I have spent hours...

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

angularjs,django,rest,django-rest-framework
I have Web application with angular as frontend and Django REST as backend. My web application does the request like /api/options/user?filter={} Now is it possible that if those requests are made from application then they go through but they type that in broswer directly and edit some filters then they...

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

django-rest-framework
I have a situation where I need to be able to POST to a resource and have a specific foreign key relation automatically "get_or_create()ed". I'm going to make up an example here for simplicity: Let's assume I want to post a new address and city is a foreign key --...

DRF Update Existing Objects

django,django-rest-framework
I'm new to DRF and python so go easy on me... I can successfully get the RoadSegment objects, but I cannot figure out how to update an existing object I have the following model: class RoadSegment(models.Model): location = models.CharField(max_length=100) entryline = models.CharField(unique=True, max_length=100) trafficstate = models.CharField(max_length=100) With the following serializer:...

Django REST error returning a list of objects

python,django,rest,django-rest-framework
I am using the Django REST framework in order to implement a game server for an android game. I have written a class, that is derived from GenericAPIView to handle a specific Http Post request. I want the request to return a list of some objects, that were previously queried...

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

python,json,django-rest-framework
Making use of the PUT-as-create mixin class provided HERE (class AllowPUTAsCreateMixin): class Tree(models.Model): myfield = models.CharField(max_length=100,unique=True) species = models.CharField(max_length=100, blank=True, default='') class TreeSerializer(serializers.ModelSerializer): class Meta: model = Tree fields = ('myfield', 'species') lookup_field = 'myfield' class TreeView(viewsets.ModelViewSet, AllowPUTAsCreateMixin): queryset = Tree.objects.all() serializer_class = TreeSerializer lookup_field = 'myfield' def update(self, request,...

ManyToMany Through Field Serialization

python,json,django,serialization,django-rest-framework
I am having problems serializing my items/orders with quantity. Results I am getting: { "id": 1, "_current_status": null, "orderitem_set": [ { "item_id": 2, "quantity": 5 }, { "item_id": 1, "quantity": 1 } ], "items": [ { "id": 2, "name": "Blue Shoe", "description": "Sweet blue shoe bro", "weight": "99.99", "price": "99.99"...

Django REST Exceptions

django,rest,django-rest-framework
I currently have some code for a view based on the Django REST Framework. Ive been using a customer exception class, but ideally I want to use the inbuilt Django REST exceptions. From the code below I feel this probably not the best or cleanest way to utilize the REST...

django rest framework - using viewsets

python,routing,views,django-rest-framework
I read about the viewsets in django, but haven't fully understood everything.. When using a viewset in django, for example - class SnippetViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = Snippet.objects.all() serializer_class = SnippetSerializer...

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

django,django-rest-framework
This may seem like a dumb question but I really feel like Django-Rest-Framework does not explain really well how it works. There is too much black box magic which confuses the configuration instructions (in my opinion). For instance, it says I can override create or update within my serializer. So...

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

python,django,django-rest-framework
This question has been SOLVED by myself after better looking at it. Please read my answer below. I am getting a "The fields option must be a list or tuple. Got str." when running my Django app. Running exactly the same code with the debugger, and if I have a...

DjangoRestFramework ModelSerializer: field-level validation is not working

django,django-models,error-handling,django-rest-framework,django-serializer
This is my serializers.py (I want to create a serializer for the built-in User model): from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', ) def validate_username(self, username): if not re.search(r'^\w+$', username): #checks if all the characters in username...

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

mysql,django,dojo,django-rest-framework,dgrid
I am developing a web application that will handle/manage a VERY LARGE data set - Currently any kind of heavy load causes the browser to lock up - whether I'm in the Django Rest Framework API or in the Dojo/Dgrid. This is kind of a dual question. I've researched and...

Creating multiple model instances in DRF3

django,django-models,django-views,django-rest-framework
1) I would like to create multiple model instances with one API call, like asked here: How do I create multiple model instances with Django Rest Framework? I tried the solution named in the link, with no success. I am trying to upload multiple files in one API call. Result:...

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

django,reactjs,django-rest-framework,refluxjs
I'm trying to post a new object via a React form using a Reflux action. That part is working fine. The object is posting as expected, however, when I try to GET that object programmatically, it doesn't seem to be accessible unless I log out, restart my local server, or...

daterange on a django-filter

python,django,django-rest-framework,django-filters
I use Django, the Django REST Framework plus django-filters (alex/django-filter). I have a model with the fields start_date and end_date and I'm trying to build a date api-endpoint which should receive a date and respond with items where (start_date < date) and (end_date > date). There is a date-range-filter (https://django-filter.readthedocs.org/en/latest/ref/filters.html#daterangefilter)...

django rest framework - adding to views.obtain_auth_token

view,override,django-rest-framework,http-token-authentication
I have implemented Token Authentication with django rest framework and I can post username and password to /api-token-auth/ and get the token. url(r'^api-token-auth/', token_views.obtain_auth_token) In addition to the token, I want to get the User object related to the returned token. How can I override/add to this view and also...

Django Rest Framework Pagination Settings - Content-Range

django,pagination,django-rest-framework
I am using DRF as server side to a Dojo/Dgrid web application. Dojo needs a content-range or range response from the server. Currently it doesn't send any and so the pagination for dgrid.grid isn't working properly. In the DRF documentation it states" Pagination links that are included in response headers,...

Python Django REST API test

python,django,testing,django-rest-framework
As my first attempt in python to create a API test, my test file currently looks like this: from django.test import TestCase, RequestFactory from customer.models import Customer, CustomerStatus from customer.views import CustomerPartialView from rest_framework.test import APIRequestFactory import pprint from django.utils import timezone class CustomerTest(TestCase) : def setUp(self) : self.factory =...

how to use django restframework as a backend for mobile apps

django,django-rest-framework
I need to built an "API". Using django restframework. API has to support multiple platforms like mobile apps, webapps. API will be used as a backend which will store all information. But my problem is how do I access users information using API. I mean normally django has user model....

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

django,django-rest-framework
I would like to have these fields optional in my form but... Error: {"name":["This field may not be blank."],"email":["This field may not be blank."]} Serializer: class StudentSerializer(ModelSerializer): name = CharField(read_only=False, required=False, allow_null=True) user = StudentUserSerializer(read_only=True) invite = StudentInviteSerializer(read_only=True) email = CharField(read_only=False, required=False, allow_null=True) class Meta: model = Student fields =...

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

python,django,django-rest-framework,django-1.7
I have two tables called Post and Reply. The users can create just one Response for each Post. The models look like this: class Post(models.Model): name = models.CharField(max_length = 100) class Reply(models.Model): post = models.ForeignKey(Post, related_name = 'replies') Now, I have a view that returns the posts, like this: class...

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

django,django-rest-framework
Right now I have the following serializer: class ShiftSerializer(serializers.ModelSerializer): confirmed_location = LocationSerializer(required=False) class Meta: model = Shift When I create a new Shift object I can pass along a basic object like this... {date_requested: "2015-06-11", employee: 4, shift_requested: 2} ...and the object gets created without issue. In an effort to...

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

python,angularjs,django,django-rest-framework
I have a model that I'm filling out step by step, it means I'm making a form wizard. Because of that most fields in this model are required but have null=True, blank=True to avoid raising not null errors when submitting part of the data. I'm working with Angular.js and django-rest-framework...

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

python,django,django-models,django-rest-framework,django-serializer
This super helpful error "ATypeError at / init() got multiple values for keyword argument 'read_only'" is occurring with the following serializers class UserSerializer(serializers.ModelSerializer): posts = serializers.HyperlinkedIdentityField('posts', lookup_field='username', read_only=True) class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'posts', ) class PostSerializer(serializers.ModelSerializer): author = UserSerializer(required=False, read_only=True) photos = serializers.HyperlinkedIdentityField('photos',...

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

django,django-views,django-rest-framework,user-registration
Suppose I want to register a user (I'm using the User model located in django.contrib.auth.models). Assume this is my serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', ) What's the difference between the following views, and which one is recommended when it comes to creating...

Assign JSON field to model variable in django

django,django-models,django-rest-framework
I am having my json like: { "name": "Rahul", "2or4": 2, } Here, How can I assign my model variable : twoOrFour to jason field value "2or4" as we can not have variable start with integer. I am new to django. I am using dJango-rest-framework for this api....

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

python,django,django-rest-framework
I am using Django REST framework and have been trying to create a view that returns a small bit of information, as well as register it on my router. I have four models which store information, and all of them have a created_time field. I am trying to make a...

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

django,angularjs,django-models,django-forms,django-rest-framework
I'm using the DjangoRestFramework. I have a UserSerialzer in my serializers.py file: from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', ) This is my urls.py file: urlpatterns = [ url(r'^$', views.HomePageView.as_view()), url(r'^users$', views.user_list.as_view()), url(r'^users/(?P<pk>[0-9]+)$', views.user_detail.as_view()), ] and this is my views.py file:...

How should I register a new user(custom) in django rest framework?

django,python-2.7,django-rest-framework,django-rest-auth
When ever I create a new User, the corresponding BaseUser is not getting created. The signal is working correctly as I have checked without the attributes department and user_type how do I go about registering the BaseUser? # models.py from django.db import models from django.conf import settings from django.contrib.auth.models import...