最近我正在开发一个移动应用程序(android)。对于后端,我正在使用Django REST。首先,我创建了一个用户API。哪个帖子用户的全名和来自Google登录名的电子邮件。我的移动应用程序的主要目标是解决用户问题。在这里,用户将从移动应用程序上传照片,该照片将保存在已注册的指定用户下。最后,我想知道如何在已注册用户下在django后端中发布图像。如果有人知道了,请发布。帮助将不胜感激。
这里是model.py
from django.db import models
# Creating krisi_user Model
class krisi_user(models.Model):
full_name = models.CharField(max_length=250)
email = models.CharField(max_length=100)
def __str__(self):
return self.full_name
此处Serializer.py
from rest_framework import serializers # imported serializers fror rest framework
from .models import krisi_user # added Model from model.py
#class for krisi_user serializer
class krisi_user_searializers(serializers.ModelSerializer):
# meta class for field which we want to show
class Meta:
model = krisi_user
fields = ('id','full_name','email')
此处views.py
from django.shortcuts import render
from rest_framework import viewsets
'''importing krisi_user model and serializers
in the views file '''
from .models import krisi_user
from .serializers import krisi_user_searializers
#class for krisi_user_view
class krisi_user_view(viewsets.ModelViewSet):
queryset = krisi_user.objects.all()
serializer_class = krisi_user_searializers
答案 0 :(得分:0)
You're gonna want to use a FileField
, as such:
profile_photo = models.FileField(
upload_to='user/profile_photo', null=True, blank=True
)
There's good documentation of the FileField
and how to use it at https://docs.djangoproject.com/en/2.1/ref/models/fields/#filefield.
答案 1 :(得分:0)
首先将ImageField添加到模型中。
1)将图像字段添加到模型中
from django.db import models
# Creating krisi_user Model
class krisi_user(models.Model):
full_name = models.CharField(max_length=250)
email = models.CharField(max_length=100)
image = models.ImageField(upload_to='images')
def __str__(self):
return self.full_name
2)修改序列化器以包括图像字段
from rest_framework import serializers # imported serializers fror rest framework
from .models import krisi_user # added Model from model.py
#class for krisi_user serializer
class krisi_user_searializers(serializers.ModelSerializer):
# meta class for field which we want to show
class Meta:
model = krisi_user
fields = ('id','full_name','email','image')
3)在您的views.py中使用APIView。要上传图像,您需要MultiPartParser,您可以将其添加到APIView。
class kriri_user_view(APIView):
parser_classes = (MultiPartParser, )
def post(self, request, format=None):
serializer = krisi_user_searializers(data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)