0

views.py

if request.is_ajax():
    testpic = TestPic.objects.get(pk=1)

    form = TestPicForm(request.POST, request.FILES, instance=testpic)
    if form.is_valid():
        form.save()

forms.py

class TestPicForm(forms.ModelForm):

    class Meta:
        from .models import TestPic
        model = TestPic
        fields = ('file', 'file_50',)

    def save(self):
        test_photo = super(TestPicForm, self).save()
        file = user_photo.file
        image = Image.open(file)
        rotated_image = image.rotate(90, expand=True)
        cropped_image = rotated_image.resize((300, 300), Image.ANTIALIAS)
        cropped_50_image = rotated_image.resize((50, 50), Image.ANTIALIAS)

        cropped_image.save(test_photo.file.path)
        file.seek(0)  
        cropped_50_image.save(test_photo.file_50.path)

        return user_photo

models.py

class TestPic(models.Model):
    file = models.ImageField(null=True, blank=True, default=None, upload_to="photo/%Y/%m/%d")
    file_50 = models.ImageField(null=True, blank=True, default=None, upload_to="photo/%Y/%m/%d")

This code is to upload a image file, to resize of it by two different size and to save it.

Sadly, It works only when there is any file on field file_50.

  1. In other words, if there is file some_file_50.jpeg on file_50 field, image file uploading does works, but in django-admin, there cannot see any change of file name on file_50 field.(file name of file field is changed.) However content of some_file_50.jpeg is changed.(I can see these changes by click image file link on django-admin) Only name of file, some_file_50.jpeg is unchangeable.

  2. When file_50 field has no file on it, it throws the error: The 'file_50' attribute has no file associated with it.

Question: How can I fix it? Thanks for reading.

ADD Traceback:

Internal Server Error: /accounts/crop/
Traceback (most recent call last):
  File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\pythonDev\project\upward\chatkaboo\authapp\views.py", line 833, in crop
    form.save()
  File "D:\pythonDev\project\upward\chatkaboo\authapp\forms.py", line 182, in save
    cropped_50_image.save(user_photo.file_50.path)
  File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\db\models\fields\files.py", line 56, in path
    self._require_file()
  File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\db\models\fields\files.py", line 38, in _require_file
    raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'file_50' attribute has no file associated with it.

ADD html, jquery ajax upload code:

  <form method="post" enctype="multipart/form-data" id="formUpload">
      <input type="file" name="file" required id="id_file">
  </form>
<script>
      $(".js-crop-and-upload").click(function () {
        var form_upload = $("#formUpload")[0];
        var form_data = new FormData(form_upload);

        form_data.append('some', "some_val");
        $.ajax({
            url:'/accounts/crop/',
            type:'post',
            dataType:'json',
            cache:false,
            processData: false,
            contentType: false,
            data:form_data,
            success:function (data) {
                console.log(data)
            }
     });
</script>
touchingtwist
  • 1,930
  • 4
  • 23
  • 38

1 Answers1

1

Looking at your save method, I don't see where you ever assign the modified file to the file_50 field of the model. I assume what you want to be doing is something more like the following?

cropped_50_image = rotated_image.resize((50, 50), Image.ANTIALIAS) 
# Assign cropped image to image_50 model field
user_photo.image_50 = cropped_50_image
user_photo.save()

This is just psuedo-code. You might need to wrap the file in order to make it a proper Django file before assigning it, as discussed here.

MrName
  • 2,363
  • 17
  • 31