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(...)
Related
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()
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.
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
Note: I am a django/python beginner
I currently have a User class in models.py that allows a user to upload an image to my app. This is supported by a form and template that allow the upload. This part is working fine. The issue is that I am receiving the image in the filefield within the model, but i need to get this image into my EnhanceImage.py file. Once there, I can process it with the code in this script to create an enhanced version with Pillow.
How should I set this up differently than what I am doing now? The goal in my mind is to get the image variable from the User class into the EnhanceImage.py file to be used for enhancement. I want to get it into the UserUploadedImage variable in the EnhanceImage.py file
I've tried just about every solution i can find online to pass the variable to the new file.
Models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from stdimage.models import StdImageField
class User(models.Model):
name = models.CharField(max_length=100)
content = models.CharField(max_length=50, default='something')
email = models.EmailField(blank=True)
password = models.CharField(max_length=50)
image = StdImageField(upload_to='images/', variations={'thumbnail': {'width': 640, 'height': 480}}, default='default.jpg')
def __str__(self):
return self.name
ImageEnhance.py
The goal of this file is to take the UserUploadedImage and overlay content using pillow.
from PIL import Image, ImageEnhance, ImageFont, ImageDraw
UserUploadedImage = I need the user uploaded image here!
foreground = Image.open("path/to/Image_to_overlay.jpg")
draw = ImageDraw.Draw(UserUploadedImage)
draw.rectangle([(-11, 420), (640, 515)], fill=(255,255,255), outline=(0,0,0))
UserUploadedImage.paste(foreground, (300, 385), foreground)
...
#more code below that isn't important for my question
Forms.py
from django.forms import ModelForm
from django import forms
from .models import User
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ['name', 'email', 'content', 'image']
Views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import User
from django.views.generic import ListView, CreateView # new
from django.urls import reverse_lazy #new
from .forms import UserForm # new
def home(request):
context = {
'users': User.objects.all()
}
return render(request, 'main/home.html', context)
class CreateUploadView(CreateView): # new
model = User
form_class = UserForm
template_name = 'main/photoupload.html'
success_url = reverse_lazy('home')
I am currently using the default CRUD operations provided by django-rest-framework. It works well with normal models but one of my model has many-many relation with another tag model. Here is the code for models
class ActivityType(models.Model):
title = models.CharField(max_length=200)
slug = models.CharField(max_length=250,unique=True)
def __unicode__(self):
return self.slug
class Activity(models.Model):
owner = models.ForeignKey('auth.user')
title = models.CharField(max_length=200)
slug = models.CharField(max_length=250,unique=True)
description = models.TextField()
tags = models.ManyToManyField(ActivityType)
created = models.DateTimeField(auto_now_add=True, blank=True)
def __unicode__(self):
return self.slug
What i want to know is what is the best method to integrate DRF with the same, if possible without writing all CRUD operations from scratch.
In your serializers.py
from rest_framework import serializers
from rest_framework import generics
from models import Activity
from models import ActivityType
class ActivityTypeSerializer(serializers.ModelSerializer):
class Meta:
model = ActivityType
fields = ('id', 'title', 'slug')
class ActivitySerializer(serializers.ModelSerializer):
tags = ActivityTypeSerializer(many=True, read_only=True)
class Meta:
model = Activity
fields = ('id', 'owner', 'title', 'slug', 'description', 'tags', 'created')
in your views.py
from rest_framework import viewsets
from serializers import ActivitySerializer
from serializers import ActivityTypeSerializer
from models import Activity
from models import ActivityType
class ActivityViewSet(viewsets.ModelViewSet):
queryset = Activity.objects.all()
serializer_class = ActivitySerializer
class ActivityTypeViewSet(viewsets.ModelViewSet):
queryset = ActivityType.objects.all()
serializer_class = ActivityTypeSerializer
and in your urls.py
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework import routers, serializers, viewsets
from rest_framework import generics
from rest_framework import viewsets, routers
from your_app.views import ActivityTypeViewSet
from your_app.views import ActivityViewSet
router = routers.DefaultRouter()
router.register(r'activitytypes', ActivityTypeViewSet)
router.register(r'activities', ActivityViewSet)
Also make sure the restframework urls are included as described in docs
urlpatterns = patterns('',
# your other urls
url(r'^api/$', include('rest_framework.urls', namespace='rest_framework')),
url(r'api/accounts/', include('rest_framework.urls', namespace='rest_framework')),
)