Send url: https://...entities/?ids=[1, 2, 3]
class EntityListSerializer(serializers.Serializer):
ids = serializers.ListSerializer(child=serializers.IntegerField())
class EntityListView(BaseView):
def get(self, request, *args, **kwargs):
query_params = request.query_params # <QueryDict: {'ids': ['[1, 2, 3]']}>
request_serializer = EntityListSerializer(data=request.query_params)
request_serializer.is_valid(raise_exception=True)
...
Resonse json:
{
"error": {
"ids": [
"Обязательное поле."
]
}
}
How to serialize it in right way?
Try:
class EntityListSerializer(serializers.Serializer):
ids = serializers.ListSerializer(child=serializers.IntegerField())
class EntityListView(BaseView):
def get(self, request, *args, **kwargs):
query_params = request.query_params
request_serializer = EntityListSerializer(data=query_params.dict())
request_serializer.is_valid(raise_exception=True)
...
Related
class getAlarmlogsFilterByDistincts(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request, *args, **kwargs):
column_name = request.data['column_name'] #just an idea, dont works
distincts_list = request.data['distincts_list'] #just an idea, dont works
column_values = [Alarmlog.objects.filter(**{column_name: x}) for x in distincts_list ]
serialized_response = AlarmlogSerializer(column_values)
return Response(serialized_response.data, status=status.HTTP_200_OK)
My view is more or less like this. I need to receive a string in column_name and a list in distincts_list (maybe in json format).
What i tried:
class AlarmlogsFilterByDistinctsSerializer(serializers.Serializer):
distincts_list = serializers.ListField()
column_name = serializers.CharField()
class getAlarmlogsFilterByDistincts(CreateAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = AlarmlogsFilterByDistinctsSerializer
def post(self, request, *args, **kwargs):
column_values = columnFilter(request.data['column_name'], request.data['distincts_list'])
response_serialized = serializers.serialize('json', column_values)
print(response_serialized)
return Response(response_serialized, status=status.HTTP_200_OK)
i've tried to use post method, but my response come out as a string:
"[{\"model\": \"alarms.alarmlog\", \"pk\": 26, \"fields\": {\"created_at\": \"2023-01-12T17:06:19.016Z\", \"updated_at\": \"2023-01-12T17:06:19.016Z\", \"name\": \"string43\", \"description\": \"string\", \"severity\": \"low\", \"type\": \"string\", \"period\": \"string\", \"value\": \"string\", \"reference\": \"string\", \"source\": 2147483647, \"third_party_id\": \"string\", \"device\": \"string\", \"extra_content\": {}, \"occurred_at\": \"2023-01-12T16:29:39.055Z\", \"equipment\": 7}}, {\"model\": \"alarms.alarmlog\", \"pk\": 27,...
ps. sorry my english
you could return the data in the following
import json
return Response(json.dumps(response_serialized), status=status.HTTP_200_OK)
As I do POST method, it returns the whole array as a response. Is it possible to return for example only the ID after successful request?
I have
{ "requestid": 1
"requestname": "Sample request",
"projectmanager": "Josh",
"creationdate": "2022-09-26T23:48:00Z" }
What if I only want to return the result as
{ "requestid": 1 }
Here's my view for reference:
class CreateRequestView(generics.CreateAPIView):
queryset = requestTable.objects.all()
serializer_class = RequestSerializer
Method create is perfect for the job. Firstfully get what a generic response returns, then modify the view's response as you please.
class CreateRequestView(generics.CreateAPIView):
queryset = requestTable.objects.all()
serializer_class = RequestSerializer
def create(self, request, *args, **kwargs):
response = super().create(request, *args, **kwargs)
return Response({"requestid": response.data['requestid']})
You can do this with JsonResponse
from django.http import JsonResponse
def your_view():
...
your_id = 1
return JsonResponse({'requestid':your_id})
I am sending files from the frontend and I want to save file location in database I am using DRF.
Currently, I am trying to save only one file but i am getting error
"'dict' object has no attribute '_committed'"
Can Anyone please give me some suggestions on what should I do?
Request Body I am getting for on file:-
{'id': "Please provide Site Contact person's Name", 'service': {'id': 3, 'service_name': 'Site
Survey', 'cost_per_kw': 1, 'min_size': 101, 'upto_size': 10000, 'tat': 5, 'creation_date':
None}, 'question': 3, 'creation_date': None, 'real_estate': 0, 'answer': 'VIkrant Patil',
'attachement': [{'name': 'Vikrant Patil - Offer Letter (1).pdf', 'size': 172518, 'url':
'blob:http://localhost:8000/cad9de5d-a12b-41a2-90f7-38deff67fd0f', '_file': {}}], 'project':
189}
My view.py logic for saving only one file:-
class ServiceProjectAnswerViewSet(viewsets.ModelViewSet):
model = ServiceProjectAnswer
serializer_class = ServiceProjectAnswerSerializer
# parser_classes = (MultiPartParser, FormParser)
def create(self, request, *args, **kwargs):
print(request.data)
instance = None
answers = request.data.copy()
data = {}
attachements = answers['attachement']
print(attachements[0])
data['answer'] = answers['answer']
data['project'] = answers['project']
data['question'] = answers['question']
serializer = self.get_serializer(data=data)
if serializer.is_valid(raise_exception=True):
try:
instance = serializer.save()
# for attachement in attachements:
AnswerAttachments.objects.create(
answer = instance,
# attachement = attachement
attachement = attachements[0]
)
except Exception as e:
print(e)
return Response(str(e), status=400)
return Response(serializer.data, status=201)
My view.py logic for saving only multiple files :-
In my responce when I a sending multiple files I am sending list of Objects every object has values which i want that is why I have use for loop to iterate.
def create(self, request, *args, **kwargs):
instance = None
print(request.data)
answers = request.data.copy()
for answer in answers:
data = {}
attachements = answer['attachement']
print(attachements,"attachement")
data['answer'] = answer['answer']
data['project'] = answer['project']
data['question'] = answer['question']
print(data,"data")
serializer = self.get_serializer(data=data)
if serializer.is_valid(raise_exception=True):
try:
instance=serializer.save()
for attachement in attachements:
print(attachement)
# attach = {}
# attach['name'] = attachement['name']
# attach['size'] = attachement['size']
# attach['url'] = attachement['url']
print(type(attachement))
AnswerAttachments.objects.create(
answer=instance,
attachement=attachement
)
except Exception as e:
print(e)
return Response(str(e), status=400)
else:
return Response({'message': ('Failed to save answers')}, status=400)
return Response('Answers are saved successfully!!', status=200)
Try something like this,
const formData = new FormData();
formData.append('file', file);
const requestOptions = {
method: "POST",
body:formData
};
Means,try to send body of request in multiform instead of application/json.
I have defined the following code in the views.py I am getting
TypeError : Object of type function is not JSON serializable
Libaries:
from django.db.models.query import QuerySet
from django.shortcuts import render
from django.http import HttpResponse , Http404 , JsonResponse
import json
from json import JSONEncoder
from FeedPost.models import trill
def home(request, *args, **kwargs):
return render(request, "feed.html", context={}, status=200)
Where the error occured
def trills_list_view(request, *args , **kwargs):
qs = trill.objects.all()
trills_list = [{"id": x.id, "name": x.name} for x in qs]
data = {
"response": trill_list
}
return JsonResponse(data)
def trill_list(request, trill_id, *args, **kwargs):
data = {
"id" : trill_id,
}
status = 200
try:
obj = trill.objects.get(id=trill_id)
data['name'] =obj.name
except:
data['message'] = "Not found"
status = 404
return JsonResponse(data, status=status)
I have to validate image. I have tried add validator to field in models.py, but python cannot migrate validator depending on class. How can I add validation in this case in views.py
validators.py
class ValidateImageSize:
MEASURE_UNIT_BYTE_MAP = {
'kb': 1024,
'mb': 1024 * 1024,
}
MEASURE_UNIT_NAME_MAP = {
'kb': 'kilobyte',
'mb': 'megabyte',
}
def __init__(self, max_size):
max_size, measure_unit = max_size.split(' ')
self.max_size = int(max_size)
self.measure_unit = measure_unit
def __call__(self, value):
if value.size > self.max_size * self.MEASURE_UNIT_BYTE_MAP[self.measure_unit]:
raise ValidationError(f'Size maximum is {self.max_size} {self.measure_unit}')
views.py
class EpisodeView(viewsets.ModelViewSet):
def create(self, request, story_id=None, *args, **kwargs):
try:
story = Story.objects.get(pk=story_id)
except Story.DoesNotExist:
raise NotFound
kwargs = {
'story': story,
'title': request.data.get('title'),
'cover': request.data.get('cover'),
}
episode = Episode.objects.create(**kwargs)
for image in dict(request.data.lists())['images']:
EpisodeImage.objects.create(episode=episode, image=image)
return Response({'episode_id': episode.id}, status=201)
At first we are going to validate all images is properly size/formatted or not and if there is no error then we will do create operation.
from .validators import ValidateImageSize
class EpisodeView(viewsets.ModelViewSet):
def create(self, request, story_id=None, *args, **kwargs):
try:
story = Story.objects.get(pk=story_id)
except Story.DoesNotExist:
raise NotFound
# now we will run image validation
custom_image_validator = ValidateImageSize() # with your desize size
for image in dict(request.data.lists())['images']:
custom_image_validator(image) # this will raise validation error if any validation error occur
# After that will do our regular work
kwargs = {
'story': story,
'title': request.data.get('title'),
'cover': request.data.get('cover'),
}
episode = Episode.objects.create(**kwargs)
for image in dict(request.data.lists())['images']:
EpisodeImage.objects.create(episode=episode, image=image)
return Response({'episode_id': episode.id}, status=201)