I tried your code with a CreateAPIView
from the django-rest-framework. After fixing all the preliminary errors that your code produces, I could not reproduce a boundary error.
Directory structure:
my_site/
myapp/
views.py
serializers.py
urls.py
models.py
mysite/
settings.py
urls.py
my_app/views.py:
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser, FormParser
from myapp.serializers import CompanySerializer
from myapp.models import Company
class CompanyCreateApiView(CreateAPIView):
parser_classes = (MultiPartParser, FormParser,) #Used to parse the Request.
queryset = Company.objects.all() #The contents of the Response.
serializer_class = CompanySerializer #Determines how the contents of the Response will be converted to json.
#Required. Defined in myapp/serializers.py
def post(self, request, *args, **kwargs):
print('data ==', request.data)
print('myjson ==', request.data["myjson"].read())
print('mydata ==', request.data["mydata"].read())
queryset = self.get_queryset()
serializer = CompanySerializer(queryset, many=True)
return Response(serializer.data)
myapp/serializers.py:
from rest_framework import serializers
from myapp.models import Company
#Directions for converting a model instance into json:
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company #The model this serializer applies to.
#By default all fields are converted to json.
#To limit which fields should be converted:
fields = ("name", "email")
#Or, if its easier you can do this:
#exclude = ('id',)
myapp/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = (
url(r'^company/', views.CompanyCreateApiView.as_view() ),
)
my_site/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls) ),
url(r'^myapp/', include("myapp.urls") ),
]
myapp/models.py:
from django.db import models
# Create your models here.
class Company(models.Model):
name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
def __str__(self):
return "{} {}".format(self.name, self.email)
my_site/settings.py:
...
...
DEFAULT_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
THIRD_PARTY_APPS = (
'rest_framework',
)
LOCAL_APPS = (
'myapp',
)
INSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
#'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
#]
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
...
...
Note that I didn't have to disable csrf tokens.
requests_client.py:
import requests
import json
from io import StringIO
my_dict = {
'admins': [
{'first_name':'john'
,'last_name':'white'
,'job_title':'CEO'
,'email':'test1@gmail.com'
},
{'first_name':'lisa'
,'last_name':'markel'
,'job_title':'CEO'
,'email':'test2@gmail.com'
}
],
'company-detail': {
'description': 'We are a renowned engineering company'
,'size':'1-10'
,'industry':'Engineering'
,'url':'http://try.com'
,'logo':''
,'addr1':'1280 wick ter'
,'addr2':'1600'
,'city':'rkville'
,'state':'md'
,'zip_cd':'12000'
,'phone_number_1':'408-393-254'
,'phone_number_2':'408-393-221'
,'company_name':'GOOGLE'
}
}
url = 'http://localhost:8000/myapp/company/'
#StringIO creates a file-like object in memory, rather than on disk:
#python3.4:
#with StringIO(json.dumps(my_dict)) as json_file, open("data.txt", 'rb') as data_file:
#python2.7:
with StringIO(json.dumps(my_dict).decode('utf-8')) as json_file, open("data.txt", 'rb') as data_file:
myfiles = [
("mydata", ("data.txt", data_file, "text/plain")),
("myjson", ("json.json", json_file, "application/json")),
]
r = requests.post(url, files=myfiles)
print(r.status_code)
print(r.text)
Output in request_client.py terminal window:
200
[{"name":"GE","email":"ge@ge.com"},{"name":"APPL","email":"appl@appl.com"}]
Output in django server window:
...
...
Quit the server with CONTROL-C.
data == <QueryDict: {'mydata': [<InMemoryUploadedFile: data.txt (text/plain)>],
'myjson': [<InMemoryUploadedFile: json.json (application/json)>]}>
myjson == b'{"admins": [{"first_name": "john", "last_name": "white", "email": "test1@gmail.com", "job_title": "CEO"},
{"first_name": "lisa", "last_name": "markel", "email": "test2@gmail.com", "job_title": "CEO"}], "company-detail":
{"description": "We are a renowned engineering company", "phone_number_2": "408-393-221", "phone_number_1": "408-393-254",
"addr2": "1600", "addr1": "1280 wick ter", "logo": "", "size": "1-10", "city": "rkville", "url": "http://try.com",
"industry": "Engineering", "state": "md", "company_name": "GOOGLE", "zip_cd": "12000"}}'
mydata == b'line 1\nline 2\nline 3\nline 4\n'
[18/Dec/2015 13:41:57] "POST /myapp/company/ HTTP/1.1" 200 75