我尝试使用Django作为后端上传照片。
我使用的模型是:
def inspection_picture_path(self, filename):
return 'inspection_{0}/{1}'.format(self.inspection.id, filename)
class InspectionPictures(models.Model):
inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE)
picture = models.FileField(upload_to=inspection_picture_path, blank=True)
def __str__(self):
return "Inspection-{}".format(self.inspection.id)
在settings.py
我有:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'master/static/master/img/inspection_pictures'),
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'master/static/master/img/inspection_pictures'),)
我尝试保存图片的view
中的功能如下:
def save_pictures(inspection, pictures):
print(pictures)
for picture in pictures['pictures']:
n_picture = InspectionPictures()
n_picture.inspection_id = inspection.id
n_picture.picture = picture
n_picture.save()
print(pictures)
给了我以下结果:
<MultiValueDict: {'pictures': [<InMemoryUploadedFile: samsung-s8.png (image/png)>, <InMemoryUploadedFile: Simulator Screen Shot 6 Jul 2017, 15.43.55.png (image/png)>]}>
因此,图像在那里,但是当我尝试保存它们时,我收到一个错误:
AttributeError:&#39; bytes&#39;对象没有属性&#39; _committed&#39;
知道我做错了吗?
更新
我在save_pictures
函数中调用的视图如下:
@token_required
@transaction.atomic
def add_inspection(request):
if request.method == "POST":
data = json.loads(request.POST.get('data'))
pictures = request.FILES
n_inspection = Inspection()
n_inspection.user_id = data['user']['id']
n_inspection.data = json.dumps(data)
n_inspection.save()
save_pictures(n_inspection, pictures)
return HttpResponse("Its ok.", status=200)
else:
return HttpResponse("Something went wrong.", status=400)
Inspection
模型是:
class Inspection(models.Model):
user = models.ForeignKey(to=User)
data = models.TextField(null=False, blank=False, default=None)
history = HistoricalRecords()
class Meta:
verbose_name_plural = "Inspections"