python pil image เป็น django imagefield แปลง

ฉันกำลังอัปโหลดรูปภาพ การอัปโหลดรูปภาพและบันทึกในโมเดล django ก็ทำงานได้ดี การสร้างภาพขนาดย่อและบันทึกเป็นอุณหภูมิ ทำเลที่ตั้งก็ใช้งานได้เช่นกัน ส่วนที่ไม่ทำงานคือการบันทึกภาพขนาดย่อ ไฟล์ถูกสร้างและบันทึก แต่เป็นไฟล์เปล่า :/ ฉันจะแก้ไขปัญหาข้อมูลที่ขาดหายไปได้อย่างไร

หากมีใครรู้วิธีแปลงอิมเมจ pil เป็นโมเดล django - imagefield โดยไม่ต้องบันทึก tmp ... โปรดบอกด้วย

def ajax_upload(request):
    if request.method == 'POST':
        newfile = Image()
        newfile.user = request.user
        file_content = ContentFile(request.raw_post_data)
        file_name = request.GET.get('file')

        newfile.image.save(file_name, file_content)

        # thumbnail creation ==========================================
        path = os.path.join(settings.MEDIA_ROOT, newfile.image.url)
        thumb_image = pil_image.open(path)

        # ImageOps compatible mode
        if thumb_image.mode not in ("L", "RGB"):
            thumb_image = thumb_image.convert("RGB")

        thumb_image_fit = ImageOps.fit(thumb_image, (32, 32), pil_image.ANTIALIAS)

        #saving temp file
        tmp_file_path = os.path.join(settings.MEDIA_ROOT, 'tmp_thumbnail.jpg')
        thumb_image_fit.save(tmp_file_path, 'JPEG', quality=75)

        #opening the tmp file and save it to django model
        thumb_file_data = open(tmp_file_path)
        thumb_file = File(thumb_file_data)

        newfile.thumbnail.save(file_name, thumb_file)
        #===============================================================

        results = {'url': newfile.image.url, 'id': newfile.id, 'width': newfile.image.width, 'height': newfile.image.height}
        return HttpResponse(json.dumps(results))
    raise Http404

person Aleksandrenko    schedule 17.04.2012    source แหล่งที่มา


คำตอบ (1)


คุณสามารถบันทึกไฟล์และกำหนดเส้นทาง (สัมพันธ์กับ MEDIA_ROOT) ไปยังฟิลด์ปลายทางได้ด้วยตนเอง

thumb_path = 'uploads/1_small.jpg'
thumb_image_fit.save(os.path.join(MEDIA_ROOT, thumb_path), 'JPEG', quality=75)
newfile.thumbnail = thumb_path

แน่นอนว่าคุณจะต้องดำเนินการทั้งหมดของ Django ด้วยตนเอง - ตรวจสอบว่ามีไฟล์อยู่หรือไม่ แก้ไขชื่อหากมี และอื่นๆ

person ilvar    schedule 18.04.2012
comment
ฉันไม่สามารถทดสอบได้ตอนนี้ แต่ newfile.thumbnail เป็น ImageField และฉันไม่คิดว่า 'newfile.thumbnail = thumb_path' จะใช้ได้ หากฉันเข้าใจถูกต้องแล้ว imagefield จะถูกบันทึกดังนี้: newfile.thumbnail.save(file_name, thumb_file) (file_name คือสตริงและ thumb_file ต้องเป็นไฟล์หรือ ContentFile) - person Aleksandrenko; 18.04.2012
comment
ใช่ obj.field.save(name, content) เป็นวิธีที่ถูกต้องมากกว่าและมีการบันทึกอย่างเป็นทางการ แต่ FileField เก็บเฉพาะเส้นทางในฐานข้อมูลและอนุญาตให้กำหนดเส้นทางนั้นได้โดยตรง มันเป็นคุณสมบัติที่ไม่มีเอกสาร แต่ใช้งานได้ - person ilvar; 19.04.2012
comment
ขอบคุณ ฉันจะจำไว้เพื่ออนาคต - person Aleksandrenko; 19.04.2012