type object ‘X’ has no attribute ‘objects’

The line notifications = Notification.objects.all() is referencing the Notification View class defined in api.py and not models.py. The easiest way to fix this error is to rename the Notification class in either api.py or models.py so that you can refer to your model properly. Another option would be to use named imports: from .models import … Read more

Django REST Framework ModelSerializer get_or_create functionality

In my experience nmgeek’s solution won’t work in DRF 3+ as serializer.is_valid() correctly honors the model’s unique_together constraint. You can work around this by removing the UniqueTogetherValidator and overriding your serializer’s create method. class MyModelSerializer(serializers.ModelSerializer): def run_validators(self, value): for validator in self.validators: if isinstance(validator, validators.UniqueTogetherValidator): self.validators.remove(validator) super(MyModelSerializer, self).run_validators(value) def create(self, validated_data): instance, _ = models.MyModel.objects.get_or_create(**validated_data) … Read more

Django Rest Framework custom authentication

How to implement a custom authentication scheme in DRF? To implement a custom authentication scheme, we need to subclass the DRF’s BaseAuthentication class and override the .authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise. In some circumstances, we may raise an AuthenticationFailed exception from the … Read more

Can to_representation() in Django Rest Framework access the normal fields

DRF’s ModelSerializer already has all the logic to handle that. In your case you shouldn’t even need to customize to_representation. If you need to customize it, I would recommend to first call super and then customize the output: class PersonListSerializer(serializers.ModelSerializer): class Meta: model = Person fields = (‘foo’, ‘bar’,) def to_representation(self, instance): data = super(PersonListSerializer, … Read more

Django Forms with ReactJS

First, i think you need to check related React documentation about forms with multiple inputs. It gives you base idea about how things should be structured in React side. About fetching data from server, you can try something like this in componentDidMount: componentDidMount() { // Assuming you are using jQuery, // if not, try fetch(). … Read more

Django Rest Framework Business Logic

It is more about design patterns rather than Django Rest Framework. Here are some tips: Providing interfaces using REST should not involve any specific code related to data manipulation or business logic. Using an MVC approach does not mean that you shouldn’t layer your application. You should be able to test your business logic without … Read more

Usage of .to_representation() and .to_internal_value in django-rest-framework?

If you want to create a custom field, you’ll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, date/time/datetime or … Read more

How to cache Django Rest Framework API calls?

Ok, so, in order to use caching for your queryset: class ProductListAPIView(generics.ListAPIView): def get_queryset(self): return get_myobj() serializer_class = ProductSerializer You’d probably want to set a timeout on the cache set though (like 60 seconds): cache.set(cache_key, result, 60) If you want to cache the whole view: from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page class ProductListAPIView(generics.ListAPIView): … Read more

Django REST Framework image upload

you can create separate endpoint for uploading images, it would be like that: class ProductViewSet(BaseViewSet, viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer @detail_route(methods=[‘post’]) def upload_docs(request): try: file = request.data[‘file’] except KeyError: raise ParseError(‘Request has no resource file attached’) product = Product.objects.create(image=file, ….) you can go around that solution — update: this’s how to upload from … Read more