How to upload a CSV file in Django using the REST API? - django

How can I send a 220,000-line CSV file to Django using the Rest Framework API? Thank you.

#Botta- How about something like this
from django.db import models
Create your models here.
class MyFile(models.Model):
file = models.FileField(blank=False, null=False,upload_to='images/')
description = models.CharField(null=True,max_length=255)
uploaded_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'MyFiles'
class MyFileView(APIView):
# MultiPartParser AND FormParser
# https://www.django-rest-framework.org/api-guide/parsers/#multipartparser
# "You will typically want to use both FormParser and MultiPartParser
# together in order to fully support HTML form data."
parser_classes = (MultiPartParser, FormParser)
def post(self, request, *args, **kwargs):
file_serializer = MyFileSerializer(data=request.data)
if file_serializer.is_valid():
file_serializer.save()
return Response(file_serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
from rest_framework import serializers
from .models import MyFile
class MyFileSerializer(serializers.ModelSerializer):
class Meta:
model = MyFile
fields = ('file', 'description', 'uploaded_at')

#Stacy Hi. I made the changes, but it didn't work. I would like the fields in the CSV file to go automatically to my models and to the REST API. I would like to import my CSV data when uploading the file. Thanks.
models.py
from django.db import models
class MyFile(models.Model):
file = models.FileField(blank=False, null=False,upload_to='images/')
description = models.CharField(null=True,max_length=255)
uploaded_at = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=150)
sex = models.CharField(max_length=150)
age = models.CharField(max_length=50)
height = models.CharField(max_length=150)
def __str__(self):
return self.description
class Meta:
verbose_name_plural = 'MyFiles'
serializers.py
from rest_framework import serializers
from .models import MyFile
class MyFileSerializer(serializers.ModelSerializer):
class Meta:
model = MyFile
fields = ("file", "description", "uploaded_at", "name", "sex", "age", "height",)

#Stacy- Hello. I was able to upload the csv file and pass it to my API as .CSV, however, I would like all fields in my CSV file to be transferred to API Rest. For example ID, Name, Age and Profile. It's possible? Thank you. Thank you.
serializers.py
from rest_framework import serializers
from .models import MyFile
class MyFileSerializer(serializers.ModelSerializer):
class Meta:
model = MyFile
fields = ('file', 'description', 'uploaded_at')
models.py
from django.db import models
class MyFile(models.Model):
file = models.FileField(blank=False, null=False,upload_to='images/')
description = models.CharField(null=True,max_length=255)
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.description
class Meta:
verbose_name_plural = 'MyFiles'
views.py
from rest_framework.parsers import MultiPartParser, FormParser
from .models import MyFile
from .serializers import MyFileSerializer
from rest_framework import generics
from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.exceptions import NotFound
from rest_framework.response import Response
from rest_framework.views import APIView
class MyFileViewSet(viewsets.ModelViewSet):
queryset = MyFile.objects.all()
serializer_class = MyFileSerializer
urls.py
from .views import MyFileViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'', MyFileViewSet)
urlpatterns = router.urls

Related

How to link to URL of related object in DRF

I’m making a music player with a DRF backend.
I have two models, one is Song and the other is TrackQueue
In the browser, the “nowplaying” instance of TrackQueue shows the meta of the queued song with a link to the file in its meta.
What I need now is a url that always produces that instance of the “nowplaying” TrackQueue (id=1)
What would that url be and how can I create it?
Thank you
models.py
class Song(models.Model):
title = models.CharField(max_length=24)
file = models.FileField()
def __str__(self):
return self.title
class TrackQueue(models.Model):
title = models.CharField(max_length=64)
is_song = models.OneToOneField(Song, on_delete=models.CASCADE)
def __str__(self):
return self.title
Serializers.py
from rest_framework import serializers
from .models import Song, TrackQueue
class SongSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Song
fields = ('id' ,'title', 'file')
class TrackQueueSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = TrackQueue
fields = ('id' , 'title', 'is_song')
views.py
from django.shortcuts import render
from .serializers import SongSerializer
from rest_framework import viewsets
from .models import Song, TrackQueue
from music.serializers import SongSerializer, TrackQueueSerializer
class SongView(viewsets.ModelViewSet):
serializer_class = SongSerializer
queryset = Song.objects.all()
class TrackQueueView(viewsets.ModelViewSet):
serializer_class = TrackQueueSerializer
queryset = TrackQueue.objects.all()

How to POST multiple data in DRF and React with Axios

I have 2 models named Recipe and Step..
I have serialized both to make an API for GET request.. I want to know is there a way to create for POST request so that I can send both the data (steps and recipe) in the same request?
models.py:
from django.db import models
class Recipe(models.Model):
title = models.CharField( max_length=50)
uuid = models.CharField( max_length=100)
def __str__(self):
return f'{self.uuid}'
class Step(models.Model):
step = models.CharField(max_length=300)
uuid = models.ForeignKey(Recipe, on_delete=models.CASCADE)
def __str__(self):
return f'{self.step} - {self.uuid}'
serializers.py:
from rest_framework import serializers
from .models import *
class RecipeSerializer(serializers.ModelSerializer):
class Meta:
model = Recipe
fields = ['title', 'uuid']
class StepSerializer(serializers.ModelSerializer):
class Meta:
model = Step
fields = ['step', 'uuid']
views.py:
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import *
from .models import *
#api_view(['GET'])
def apiOverview(request):
api_urls = {
'List':'/recipe-list/',
'Detail View':'/recipe-detail/<str:pk>/',
'Create':'/recipe-create/',
'Update':'/recipe-update/<str:pk>/',
'Delete':'/recipe-delete/<str:pk>/',
'Steps' : '/steps/<str:pk>'
}
return Response(api_urls)
#api_view(['GET'])
def recipeList(request):
recipes = Recipe.objects.all()
serializer = RecipeSerializer(recipes, many=True)
return Response(serializer.data)
#api_view(['GET'])
def recipeDetail(request, pk):
recipe = Recipe.objects.get(uuid=pk)
recipe_serializer = RecipeSerializer(recipe, many=False)
steps = Step.objects.filter(uuid=pk)
steps_serializer = StepSerializer(steps, many=True)
return Response({
'recipe' : recipe_serializer.data,
'steps' : steps_serializer.data
})
How can I create a view for POST and handle both the models?
Try:
from rest_framework import generics
from .models import *
class StepAndRecipe(generics.CreateAPIView):
queryset = Step.objects.all()
queryset = Recipe.objects.all()
serializer_class = StepSerializer
serializer_class = RecipeSerializer
Add in urls.py:
from django.urls import path
from .views import StepAndRecipe
urlpatterns = [
path('steprecipepost', StepAndRecipe.as_view(), name='steps_recipes')
This will only work with POST! And one more thing: take care with the raw data and the HTML form, maybe theses get a little confused since you are using two models in the same view.

DRF -django rest framework APi multiple file upload through API [duplicate]

This question already has answers here:
How to upload multiple Images using DJango Rest Framework?
(3 answers)
Closed 2 years ago.
I am trying to upload multi-images to a single post which currently I am being able to upload only single image and get the confirmation through API. How can I make this to multi upload ?
My models.py
from django.db import models
# Create your models here.
class UploadedImage(models.Model):
img = models.ImageField('Uploaded Image', upload_to='images') # stores uploaded image
dt_created = models.DateTimeField(auto_now_add=True, verbose_name='Created')
my serializers.py
from rest_framework import serializers
from .models import UploadedImage
class UploadedImageSerializer(serializers.ModelSerializer):
class Meta:
model = UploadedImage
fields = ('pk', 'img', 'dt_created')
my viewsets.py
from django.shortcuts import render
from rest_framework import viewsets
from imageUpload.serializers import UploadedImageSerializer
from imageUpload.models import UploadedImage
# Create your views here.
class UploadImageViewset(viewsets.ModelViewSet):
queryset = UploadedImage.objects.all()
serializer_class = UploadedImageSerializer
you can do this
My models.py
from django.db import models
# Create your models here.
class UploadedImage(models.Model):
img = models.ImageField('Uploaded Image', upload_to='images') # stores uploaded image
dt_created = models.DateTimeField(auto_now_add=True, verbose_name='Created')
my serializers.py
from rest_framework import serializers
from .models import UploadedImage
class UploadImagesSerializer(serializers.Serializer):
# here we limit how maximum the image is
img = serializers.ImageField()
img1 = serializers.ImageField(required=False)
img2 = serializers.ImageField(required=False)
def create(self, validated_data):
create = YourModel(img=validated_data.get("img"))
create.save()
if validated_data.get("img1"):
create = YourModel(img=validated_data.get("img1"))
create.save()
....
return create
class UploadedImageSerializer(serializers.ModelSerializer):
class Meta:
model = UploadedImage
fields = ('pk', 'img', 'dt_created')
my viewsets.py
from django.shortcuts import render
from rest_framework import viewsets
from imageUpload.serializers import UploadedImageSerializer, UploadImagesSerializer
from imageUpload.models import UploadedImage
from rest_framework import parsers
# Create your views here.
class UploadImageViewset(viewsets.ModelViewSet):
queryset = UploadedImage.objects.all()
serializer_class = UploadedImageSerializer
parser_class = [parsers.JSONParser, parsers.MultiPartParser,]
def create(self, request):
serializer = UploadImagesSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(...)
return Response(...)

File Upload using Django Rest Framework getting error "No file was submitted."

While trying to upload the file using Postman with Content-Type - multipart/form-data in the headers. I am passing both the fields, but I get the following error:
Error:{"upload_to": ["This field is required."],"file_object": ["No
file was submitted."]}
urls.py
from django.conf.urls import include, url
from rest_framework_nested import routers
from utils.views import TemporaryImageView
from . import views
router = routers.SimpleRouter(trailing_slash=False)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^upload-temp-image/$', TemporaryImageView.as_view())
]
views.py
from rest_framework import viewsets, filters
import django_filters.rest_framework
from rest_framework.generics import CreateAPIView
from rest_framework.parsers import FileUploadParser, MultiPartParser, FormParser
from utils.serializers.temporary_image import TemporaryImageSerializer
class TemporaryImageView(CreateAPIView):
parser_classes = (MultiPartParser,)
serializer_class = TemporaryImageSerializer
serializers.py
from rest_framework import serializers
from utils.models.tempfile import TemporaryFile
class TemporaryImageSerializer(serializers.ModelSerializer):
choices = (('Company Logo','/company/logos/'),
)
upload_to = serializers.ChoiceField(choices=choices)
file_object = serializers.ImageField()
class Meta:
model = TemporaryFile
fields = ('upload_to', 'file_object')
models.py
from django.db import models
class TemporaryFile(models.Model):
"""
a temporary file to backend
"""
file_object = models.FileField(blank=False, null=False)
timestamp = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return str(self.id)
Please help...I don't know what is wrong.
I have changed my models.py file in the way below and it works as expected..
models.py
from django.db import models
def get_image_path(instance, filename):
if instance.upload_to == "company_logo":
path = 'company/logo/'
return path
class TemporaryFile(models.Model):
"""
a temporary file to backend
"""
file_object = models.FileField(blank=False, null=False, upload_to=get_image_path)
timestamp = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return str(self.id)
def __init__(self, *args, **kwargs):
self.upload_to = kwargs.pop("upload_to")
super(TemporaryFile, self).__init__(*args, **kwargs)

Django 1.11.2 serializer nested json array

I am new to both Python and Django and I would appreciate some guidance with a problem I'm having with Django REST, nested JSON and the serializer.
I wish to post:
{ "Server": [
{
"serverSerialNumber": "0000",
"serverUniqueKey": "2222"
},
{
"serverSerialNumber": "0001",
"serverUniqueKey": "2223"
}
]
}
This is my serializer:
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from .models import Api
class ApiSerializer(serializers.ModelSerializer):
"""Serializer to map the Model instance into JSON format."""
class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Api
fields = ('id', 'serverSerialNumber', 'serverUniqueKey', 'date_created', 'date_modified')
read_only_fields = ('date_created', 'date_modified')
depth = 1
I simply receive the following back:
{
"serverSerialNumber": [
"This field is required."
]
}
So I am not understanding how to use 'depth' or I'm doing something silly.
Adding View per request:
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import generics
from .serializers import ApiSerializer
from .models import Api
class CreateView(generics.ListCreateAPIView):
"""This class defines the create behavior of our rest api."""
queryset = Api.objects.all()
serializer_class = ApiSerializer
def perform_create(self, serializer):
"""Save the post data when creating a new item."""
serializer.save()
Ok, so I've stumbled through some documentation and had another bash at this.
Still not working but the code seems to make more sense, here is the new code and error:
serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from .models import Blade, Servers
class BladeSerializer(serializers.ModelSerializer):
class Meta:
model = Blade
fields = ('id', 'serverSerialNumber', 'serverUniqueKey', 'date_created', 'date_modified')
read_only_fields = ('date_created', 'date_modified')
class ServersSerializer(serializers.ModelSerializer):
Server = BladeSerializer(many=True)
class Meta:
model = Servers
fields = ['Server']
def create(self, validated_data):
servers_data = validated_data.pop('Server')
srv = Servers.objects.create(**validated_data)
for server_data in servers_data:
Blade.objects.create(srv=srv, **server_data)
return srv
views.py
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from api.serializers import UserSerializer, GroupSerializer
from rest_framework import generics
from .serializers import BladeSerializer, ServersSerializer
from .models import Blade, Servers
class CreateView(generics.ListCreateAPIView):
queryset = Servers.objects.all()
serializer_class = ServersSerializer
def perform_create(self, serializer):
serializer.save()
models.py
from django.db import models
from inventory.models import Server
class Blade(models.Model):
instanceId = models.CharField(max_length=255, blank=True, unique=False)
chassisUniqueKey = models.CharField(max_length=255, blank=True, unique=False)
serverUniqueKey = models.CharField(max_length=255, blank=True, unique=False)
serverSerialNumber = models.CharField(max_length=255, blank=False, unique=True)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return "{}".format(self.name)
class Servers(models.Model):
Servers = models.CharField(max_length=10, blank=True, unique=False)
def __str__(self):
"""Return a human readable representation of the model instance."""
return "{}".format(self.name)
The error
Got AttributeError when attempting to get a value for field Server on serializer ServersSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Servers instance.
Original exception text was: 'Servers' object has no attribute 'Server'.
Try this,
class CreateView(generics.ListCreateAPIView):
queryset = Api.objects.all()
serializer_class = ApiSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data, many=True)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
serializer.save()