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...
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...
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...
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,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...
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...
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 ...
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)...
You would use a nested serializer for that. All serializers in DRF are also usable as fields: class TrackSerializer(ModelSerializer): class Meta: model = Track fields = ('id', 'href') class YourModelSerializer(ModelSerializer): tracks = TrackSerializer(many=True) You have examples in the official documentation, pretty close to that by the way. If you want...
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...
I should have used the ModelViewSet: class ListingViewSet(viewsets.ModelViewSet): ^^^^^ Thanks to xordoquy for pointing it out in the issue I opened....
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...
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()) ...
Got it. Move from http to https wasn't reflected in the URL.
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,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,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)...
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...
python,django,django-rest-framework,overriding
Hmm. this might not be the perfect answer given I don't know how you want to pass this "extra" in (ie. is it an extra field in a form normally, etc) What you'd probably want to do is just represent foo as a field on the serializer. Then it will...
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...
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,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,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,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...
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...
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,python-2.7,django-rest-framework
meta does not equal Meta. Python is case-sensitive.
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-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...
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...
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' ) ...
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...
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...
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] ...
rest,authentication,login,django-rest-framework
In a normal web application (removing the API from the question), a user would "log" in with their credentials (username/password, social tokens, etc.) and would receive a session cookie (assigned by Django) that allows them to authenticate in future requests on behalf of a user (realistically, themselves). This session cookie...
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...
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...
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,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,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...
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...
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,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,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 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
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...
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...
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...
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,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...
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...
python,django,django-rest-framework
You are including the pictures field on the ImageSerializer, but you are not telling Django REST framework that it can accept multiple values. You should pass many=True into the field when initializing it class ItemImageSerializer(serializers.ModelSerializer): class Meta: model = ItemImage fields =( 'picture', ) class ItemSerializer(ObjectReviewsSerializer): pictures = ItemImageSerializer(many=True) ......
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...
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...
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,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...
python,django,django-rest-framework
you can get the resolved url from the request object request.resolver_match.view_name ...
python,testing,django-rest-framework
You are sending a list of files to the view, but you aren't sending them correctly. When you send data to a view, whether it is a Django view or DRF view, you are supposed to send it as a list of key-value pairs. { "key": "value", "file": open("/path/to/file", "rb"),...
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,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...
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....
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....
python,django,django-rest-framework
DRF does not clearly state what required stands for for lists. In its code, it appears that validation passes as long as a value is supplied, even if that value is an empty list. If you want to ensure the list is not empty, you'll need to validate its content...
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...
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....
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...
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) ...
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...
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...
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...
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') ...
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...
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 =...
The method name is has_permission not has_permissions (no s) ;)
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...
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...
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...
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,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...
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),...
python,routing,views,django-rest-framework
You access those actions by specifying the corresponding HTTP method, which is a core idea in REST. Namely, using the HTTP methods to do what their name implies. GET /snippets/ - list the snippet objects POST /snippets/ with POST data - create a new object PATCH /snippets/ with data -...
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...
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,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....
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/',...
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!...
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...
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...
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...
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...
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,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...
django,python-2.7,django-rest-framework,django-rest-auth
If all users are going to have these types I'd just suggest extending with a custom user model for less serializer related headaches (especially if you want to be able to just POST/PUT to /user/ to change these fields and don't want to go through the exercise of extending your...