我的目标是如何在用户不想提交图像的情况下将ImageField((设置为可选。
当我使用django Forms时,ImageField((将正常工作,其中字段将被视为可选字段。然而,当我使用Django时;类FleetSerializer(serializers.ModelSerializer(:";则ImageField((将不会被视为可选。
我的这个巨大问题有什么解决方案吗?非常感谢。
这是完整的代码:MODEL、SERIALIZERS、VIEWS,其中我的目标是让REST API具有可选字段"licRegImage"。这个代码是针对Flutter/Dart前端的,为什么我更喜欢使用SERIALIZERS。
两个多星期以来,我一直找不到解决方案。我怀疑这可能与兼容性问题或最严重的错误有关。
- 来自Requirements.txt:
- Django==3.2.16
- djangorestframework==3.13.1
- djongo==1.3.6
- pymongo==3.12.1
- djangorestframework==3.13.1
- 枕头==9.2.0
- 等等。,等等
型号:
from djongo import models
class Fleet(models.Model):
usrRegId = models.CharField(max_length=28)
fleetId = models.CharField(max_length=13)
vinNr = models.CharField(max_length=35)
licRegNr = models.CharField(max_length=35)
licRegExpire = models.CharField(max_length=10)
licRegImage = models.ImageField(null=True, blank=True, upload_to='astfleet/imglicReg/', default = 'sys_global/images/no_image.png')
objects = models.DjongoManager()
class Meta:
db_table = "ast_fleet"
def __str__(self):
return self.usrRegId
序列化程序:
class FleetRegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = Fleet
fields =(
'usrRegId',
'fleetId',
'vinNr',
'licRegNr',
'licRegExpire',
'licRegImage',
)
extra_kwargs = {
'usrRegId':{'write_only':True},
'fleetId':{'write_only':True},
'licRegImage':{'required':False},
}
视图:
class astFleetRegistration(APIView):
permission_classes = [IsAuthenticated]
def post(self, request):
newFleet = {
'usrRegId' : request.user.usrRegId,
'fleetId' : fleetId_new,
'vinNr' : request.data['vinNr'],
'licRegNr' : request.data['licRegNr'],
'licRegExpire' : request.data['licRegExpire'],
'licRegImage' : request.data['licRegImage'],
}
serializers = FleetRegistrationSerializer(data=newFleet)
if serializers.is_valid():
serializers.save()
getResponse = {'SUCCESS' : 0,
'MESSAGE' : 'New fleet was successfully registered',
'ACTION' : 'Check your Email for details',
'DATA' : [serializers.data]}
return JsonResponse(getResponse, status=status.HTTP_200_OK, safe=False)
getResponse = { 'SUCCESS' : 1,
'MESSAGE' : 'Input cannot be serialized',
'ACTION' : 'Please check your input and submit again'}
return JsonResponse(getResponse, status=status.HTTP_400_BAD_REQUEST)
当您使用django-rest框架时,它期望图像为base64文件
因此您可以使用django-extra-fields
库将图像转换为base64并将其存储为
django额外字段参考