When I receive a POST request on a Django REST framework APIView class, I would like to filter/validate the parameters that are passed to prevent them from being modified. For example, for this serializer:
class MediaSerializer(serializers.ModelSerializer):
class Meta:
model = Media
fields = ('id', 'title', 'content', 'url', 'createdByUser', 'karma', 'type', 'issue', 'creationDate', 'updatedDate')
Some parameters such as the id, creationDate or createdByUser shouldn't be modified. So for my class class MediaDetail(APIView) I have:
def validateRequest(self):
user = self.request.data.get('createdByUser', None)
karma = self.request.data.get('karma', None)
creationDate = self.request.data.get('creationDate', None)
if user is not None or karma is not None or creationDate is not None:
return Response(status=status.HTTP_400_BAD_REQUEST)
#method_decorator(login_required)
def post(self, request, pk, format=None):
self.validateRequest()
media = self.get_object(pk)
self._throwIfNotMediaAuthor(media, request.user)
serializer = MediaSerializer(media, data=request.data)
if serializer.is_valid():
# serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Is there a better way to make this validation? Maybe on the serializer? I couldn't find enough documentation.
Yes, you can use the read_only_fields parameter on your serializer's Meta.
Example on how to use inside your current view (modified it a little assuming you want to create an object when POSTing as per REST's guidelines):
class MediaSerializer(serializers.ModelSerializer):
class Meta:
model = Media
read_only_fields = ('id', 'karma', 'createdByUser', 'creationDate')
...
#method_decorator(login_required)
def post(self, request, pk, format=None):
serializer = MediaSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(createdByUser=request.user, creationDate=timezone.now().date(), karma=initial_value)
return Response(serializer.data, status=status.HTTP_201_CREATED)
Related
DRF returning this: get() returned more than one Product -- it returned 2!, when im trying to get objects from my DB by PK
Serializers
class ProductSerializer(serializers.ModelSerializer):
# cat_id = serializers.SlugRelatedField(slug_field='cat_id', read_only=True)
class Meta:
model = Product
fields = ('name', 'description', 'cat_id', 'use', 'diametr', 'len', 'color', 'photo')
Views
class CategoryProductView(APIView):
def get(self, request, pk):
product = Product.objects.get(cat_id=pk)
serializer = ProductSerializer(product)
return Response(serializer.data)
Urls
path('api/categorylist/<int:pk>', CategoryProductView.as_view())
If you want to serialize all items belonging to a certain primary key of a category, you filter, and serialize many=True items, so:
class CategoryProductView(APIView):
def get(self, request, pk):
products = Product.objects.filter(cat_id=pk)
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
I have a API view in place where I first want to create a new user (already working) and second I want to return the new created user object using my UserSerializer (Not working).
views.py
#api_view(['POST'])
#permission_classes([AllowAny])
def user_create(request):
exception_handler = UserUnavailable
success_handler = UserCreated
if request.method == 'POST':
creation_serializer = CreateUserSerializer(data=request.data)
try:
if creation_serializer.is_valid(raise_exception=True):
creation_serializer.save()
user_serializer = UserSerializer(data=creation_serializer.instance.id)
if user_serializer.is_valid():
return JsonResponse({"status_code": success_handler.status_code,
"default_detail": success_handler.default_detail,
"default_code": success_handler.default_code,
"new_user": user_serializer,
}, safe=False)
except APIException:
return JsonResponse({"status_code": exception_handler.status_code,
"default_detail": exception_handler.default_detail,
"default_code": exception_handler.default_code
}, safe=False)
I can confirm that creation_serializer.instance.id contains the new users id.
serializers.py
class UserSerializer(serializers.ModelSerializer):
id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
class Meta:
model = get_user_model()
fields = ('id', 'user')
read_only_fields = ('id', 'user')
I can also confirm that
if user_serializer.is_valid()
does not validate for some reason. Any ideas
Thanks in advance
To initialize a serializer with user instance instead of
user_serializer = UserSerializer(data=creation_serializer.instance.id)
You should write something like this:
user_serializer = UserSerializer(instance=creation_serializer.instance)
instead of
Also, you don't have to validate the object that has already been saved.
And create a response you should like this:
return JsonResponse({
"status_code": success_handler.status_code,
"default_detail": success_handler.default_detail,
"default_code": success_handler.default_code,
"new_user": user_serializer.data,
}, safe=False)
But using api_view is now a bad thing. It's much better to use ModelViewSet. You can use something like this:
class UserViewSet(ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
def get_serializer_class(self, *args, **kwargs):
if self.action == 'create':
return CreateUserSerializer
return super().get_serializer_class(*args, **kwargs)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
response_serializer = self.serializer_class(instance=serializer.instance)
return Response(response_serializer.data, status=status.HTTP_201_CREATED, headers=headers)
And I'm sorry, I haven't tested it, there might be typos.
You can read about ModelViewsets more here https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset
I have the following two classes and I want two merge EventInvitationCreateView into EventInvitationViewSet.
However, I am struggling to bring perform_create into create_invitation as I still need to access serializer. Do you have any input on how to achieve that?
class EventInvitationCreateView(CreateAPIView):
serializer_class = InvitationSerializer
permission_classes = [RetoolPermission]
queryset = Invitation.objects.none()
def perform_create(self, serializer):
email = serializer.validated_data["email"]
event = self.request.event
invitation_exists = Invitation.objects.filter(
email__iexact=email, event=event
).exists()
if invitation_exists:
raise ValidationError("Email already exists")
serializer.save(event=event)
class EventInvitationViewSet(
mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet
):
permission_classes = [RetoolPermission]
serializer_class = InvitationSerializer
filter_backends = [filters.SearchFilter]
search_fields = ["email"]
queryset = Invitation.objects.none()
def get_queryset(self) -> QuerySet:
return self.request.event.invitations.all()
#action(detail=True, methods=["post"])
def create_invitation(self, request, pk=None):
[...perform_create]
the action is still a standard view's method, so you can use self.get_serializer()
for instance
#action(detail=True, methods=["post"])
def create_invitation(self, request, pk=None):
s = self.get_serializer(data=request.data)
....
If you need to use a "action specific serializer" you can specify the serializer class in the decorator
#action(detail=True, methods=["post"], serializer_class=MyOtherSerializer)
def create_invitation(self, request, pk=None):
s = self.get_serializer(data=request.data) # <-- instance of MyOtherSerializer
....
I want to set user_id field using JWT token and store in database table when new reservation is created. there can be single or multiple reservation request.
whenever user create reservation i want to store there user_id in our table. currently there is no foreign key associated with it. it is simply an integer field.
I am able to fetch user_id from JWT.but its not updating in database
I know this question had been asked previously i tried all the answer of previous post but its not working for me. i dont know why
model.py
class reservations(models.Model):
pet_id=models.IntegerField()
user_id=models.IntegerField(default=0)
location=models.PositiveSmallIntegerField()
arrival=models.DateTimeField()
depature=models.DateTimeField()
comments=models.TextField(max_length=200)
view.py
class requestReservation(CreateAPIView):
serializer_class = requestReservationSerailizer
permission_classes = [IsAuthenticated]
def create(self, request, *args, **kwargs):
serializer = requestReservationSerailizer(data=request.data,context={'user_id': request.user.id}, many=True)
if not serializer.is_valid(raise_exception=False):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({"message":"Success","status_message":"Reservation Created Successfully"},status=status.HTTP_200_OK)
serializer.py
class requestReservationSerailizer(ModelSerializer):
user_id = SerializerMethodField('set_user_id')
class Meta:
model=reservations
fields = [
'pet_id',
'user_id',
'location',
'arrival',
'depature',
'comments',
]
def set_user_id(self, obj):
obj.user_id = self.context.get("user_id")
return obj.user_id
currently it is simply storing user_id as 0 which is default set in model.
SerializerMethodField is read-only by default, here's a quick look at the source code:
def __init__(self, method_name=None, **kwargs):
self.method_name = method_name
kwargs['source'] = '*'
kwargs['read_only'] = True
super(SerializerMethodField, self).__init__(**kwargs)
Assuming you want to read and write into this field; remove the SerializerMethodField overriding from the serializer declaration; and set the user_id in your view
class requestReservationSerailizer(ModelSerializer):
class Meta:
model=reservations
fields = [
'pet_id',
'user_id',
'location',
'arrival',
'depature',
'comments',
]
def create(self, request, *args, **kwargs):
data = request.data.copy()
for datum in data:
datum['user_id'] = request.user.id
serializer = requestReservationSerailizer(data=data, many=True)
if not serializer.is_valid(raise_exception=False):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({"message":"Success","status_message":"Reservation Created Successfully"},status=status.HTTP_200_OK)
Ofcourse; if you don't want your view to be doing this (and I'd agree with you here), then pass it in context (explicit) or use self.request.user.id and override validate_user_id
class requestReservationSerailizer(ModelSerializer):
class Meta:
model=reservations
fields = [
'pet_id',
'user_id',
'location',
'arrival',
'depature',
'comments',
]
def validate_user_id(self, value):
user_id = self.context.get('user_id', None) # Assuming you continue to pass it in context
if user_id is None:
# Handle error
return user_id
# You can also do this; might raise an AttributeError if the user is not authenticated:
# return self.request.user.id
I need to update categories in many Article in one request.
In ArticleViewSet I have:
def get_serializer_class(self):
if self.action in ['partial_update', 'update']:
return ArticlePostSerializer
return ArticleSerializer
So ArticlePostSerializer need to be changed.
This is my serializers code:
class ArticleShortCategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = 'id', 'name'
class ArticleSerializer(serializers.ModelSerializer):
categories = serializers.SerializerMethodField()
def get_categories(self, obj):
return ArticleShortCategorySerializer(obj.categories, many=True).data
class Meta:
model = Article
read_only_fields = 'id'
fields = ('categories', 'text') + read_only_fields
class ArticlePostSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = 'id', 'categories', 'text'
I tried to add:
class ArticlePostListSerializer(serializers.ListSerializer):
and
class Meta:
list_serializer_class = ArticlePostListSerializer
But it doen't work.
How to change this code to do multiple update.
My json request
{
[id: 90, categories: [10,12,14]],
[id: 93, categories: [10,12,14]],
[id: 95, categories: [10,12,14]]
}
Here is sample of CreateMixins OR UpdateMixins you requested.
======================= VIEW ================================
class OrderCreate(mixins.CreateModelMixin,viewsets.GenericViewSet):
pagination_class = None
def get_queryset(self):
return []
def get_serializer_class(self):
return serializers.OrderSerializer
======================= Serializer =============================
class OrderDetailSerializer(serializers.ModelSerializer):
class Meta:
model = crm_models.OrderDetail
fields = (
'product',
'quantity',
'rate_per_unit',
'order_quantity'
)
class OrderSerializer(serializers.ModelSerializer):
order_details = OrderDetailSerializer(many = True)
class Meta:
model = crm_models.OrderMaster
fields = (
'order',
'invoice_number',
'client',
'beat_check',
'target_customer',
'order_editor_client_employee',
'order_marked',
'order_saved',
'edit_marked',
'edit_saved',
'adhoc',
'order_details'
)
def create(self, validated_data,*args,**kwargs):
ordersdetails_data = validated_data.pop('order_details')
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
validated_data['client'] = user.client
validated_data['order_editor_client_employee'] = user
validated_data['adhoc'] = validated_data['adhoc'] if 'adhoc' in validated_data else False
orderObj = super(OrderSerializer, self).create(validated_data,*args,**kwargs)
orderdetails = []
for details in ordersdetails_data:
orderdetails.append(crm_models.OrderDetail(
product= details['product'],
quantity = details['quantity'],
rate_per_unit = details['rate_per_unit'],
order_quantity = details['order_quantity'],
order = orderObj
))
crm_models.OrderDetail.objects.bulk_create(orderdetails)
return orderObj
In Update view function name would be changed to update, you can find more documentation http://www.django-rest-framework.org/api-guide/generic-views/#createmodelmixin
I found K. Moe's answer to this question: Django Rest Framework POST Update if existing or create much easier to understand and implement. You only need to add a create method in the serializer and use mixins.CreateModelMixin, generics.GenericAPIView in the view. Then you can use a POST request, instead of PUT/PATCH. It allows to create AND update data stored in your database. My code for the view:
class ZipCodeList(mixins.CreateModelMixin, generics.GenericAPIView):
def post(self, request, format=None):
is_many = isinstance(request.data, list)
if is_many:
serializer = ZipCodeSerializer(data=request.data, many=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
serializer = ZipCodeSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#Greg Holst, why so much duplication? Why not:
class ZipCodeList(mixins.CreateModelMixin, generics.GenericAPIView):
def post(self, request, format=None):
serializer = ZipCodeSerializer(data=request.data, many=isinstance(request.data, list))
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Anyway, that only worked for me for creating new objects, didn't work to create-or-update in one sweep (it kept telling me these objects already exist), so this is what I did:
class ContributorSyncListAPIView(ListAPIView):
permission_classes = (isSuperUserPermission,)
allowed_methods = ("GET", "PUT")
lookup_field = "airtable_id"
serializer_class = ContributorSyncSerializer # Doesn't get used in Put, just in Get.
model = Contributor
def get_queryset(self):
return self.model.objects.all()
def put(self, request, format=None):
objects = list(request.data)
# objects is a list of OrderedDicts
try:
for o in objects:
try:
instance = self.model.objects.get(
**{self.lookup_field: o.get(self.lookup_field)}
)
for key, value in o.items():
setattr(instance, key, value)
except self.model.DoesNotExist:
instance = self.model(**o)
instance.save()
return Response(objects, status=status.HTTP_200_OK)
except Exception as e:
return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
Note my code above is very light on validation just because it was for a process of syncing models from one environment to another by a superuser, different environments with an identical codebase; so the assumption was the data had already been validated when the data was entered into the first environment. For any other purpose you'd want to validate more. But this is what I had to do to handle a list of objects that may need to be created or updating, on an object-by-object basis.