Home > front end >  Django POST method for bulk creation using postman
Django POST method for bulk creation using postman

Time:07-28

I have POST method in views.py in django to create an entry in database I can create a single entry using postman, but can not create bulk entries using postman can anyone help, please?

models.py file

from django.db import models

class Users(models.Model):
    user = models.CharField(max_length=50,default='')
    function = models.CharField(max_length=50,default='')
    department = models.CharField(max_length=50,default='')
    logon = models.CharField(max_length=50,default='')
    
    def __str__(self):
        return self.user " - Last_Logon: " self.logon
    
    
    class Meta:
        ordering = ('id',)

serializers.py file

from rest_framework import serializers
from activities.models import Users

class UsersSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Users
        fields = ('id', 'user', 'function', 'department', 'logon')

views.py file with GET,POST,PUT,DELETE, from this file POST method creates only a single entry

from django.shortcuts import render
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status
from activities.models import Users
from activities.serializers import UsersSerializer
from rest_framework.decorators import api_view
@api_view(['GET', 'POST'])
def users_list(request):
    if request.method == 'GET':
        users = Users.objects.all()

        user = request.GET.get('user', None)
        if user is not None:
            users = users.filter(user__icontains=user)

        users_serializer = UsersSerializer(users, many=True)
        return JsonResponse(users_serializer.data, safe=False)
        # 'safe=False' for objects serialization

    elif request.method == 'POST':
        users_data = JSONParser().parse(request)
        users_serializer = UsersSerializer(data=users_data)
        if users_serializer.is_valid():
            users_serializer.save()
            return JsonResponse(users_serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(users_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
@api_view(['GET', 'PUT', 'DELETE'])
def users_detail(request, pk):
    try:
        users = Users.objects.get(pk=pk)
    except Users.DoesNotExist:
        return JsonResponse({'message': 'The user does not exist'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        users_serializer = UsersSerializer(users)
        return JsonResponse(users_serializer.data)

    elif request.method == 'PUT':
        users_data = JSONParser().parse(request)
        users_serializer = UsersSerializer(users, data=users_data)
        if users_serializer.is_valid():
            users_serializer.save()
            return JsonResponse(users_serializer.data)
        return JsonResponse(users_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        users.delete()
        return JsonResponse({'message': 'User was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT)

urls.py file

from django.urls import re_path
from activities import views

urlpatterns = [
    re_path(r'^api/activities$', views.users_list),
    re_path(r'^api/activities/(?P<pk>[0-9] )$', views.users_detail),
]

if I set many=True in user serializer, UsersSerializer(data=users_data, many=True) for POST metho

In postman, for sending a single entry, got this error enter image description here

for sending multiple entries, got this error

enter image description here

CodePudding user response:

for UsersSerializer(data=users_data, many=True) you must send list of json objects

[
    {
        "User": "user1",
        "function": "t",
        "deportment": "t",
        "logon": "23...."
    }, 
    {
        "User": "user1",
        "function": "t",
        "deportment": "t",
        "logon": "23...."
    }
]

and for a user UsersSerializer(data=users_data)

you can split serializers with a send a query param into your url and in view function

if request.GET.get('bulk'):
    serializer = UsersSerializer(data=users_data, many=True)
else:
    serializer = UsersSerializer(data=users_data)
  • Related