Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class AddItemSchema(Schema): # схема для создания товара
- title = fields.Str(validate=Length(1, 64), required=True)
- description = fields.Str(validate=Length(1, 1024), required=True)
- price = fields.Int(validate=Range(1, 1000000), required=True)
- @method_decorator(csrf_exempt, name='dispatch')
- class AddItemView(View):
- """View для создания товара."""
- def post(self, request):
- try:
- document = json.loads(request.body)
- schema = AddItemSchema(strict=True)
- data = schema.load(document) # получаем словарь с данными
- new_item = Item.objects.create(**data.data) # создаем объект в бд
- new_item.save()
- return JsonResponse({'id': new_item.id}, status=201)
- except json.JSONDecodeError:
- return JsonResponse({'errors': 'Invalid JSON'}, status=400)
- except MarshErr as exc:
- return JsonResponse({'errors': exc.messages}, status=400)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement