简体   繁体   中英

Django ModelForm for updating model doesn't save Image and throws an error

I use Django 1.8.15 and python 2.7.12. I have a model:

class Page(models.Model):
    title = models.CharField(max_length=255,)
    description = models.TextField(blank=True,)
    img = models.ImageField(upload_to="img/", blank=True, null=True)
    ...

    def save(self, *args, **kwargs):
        try:
            this = Page.objects.get(id=self.id)
            if this.img != self.img:
            this.img.delete(save=False)
        except: pass
        super(Page, self).save(*args, **kwargs)

ModelForm for updating my model:

class PageForm(forms.ModelForm):
     class Meta:
         model = Page
         fields = ('title', 'description', 'img')

view:

def page_update_view(request, template, id):
    mypage = get_object_or_404(Page, id=id)
    context_dict = {}
    form = PageForm(instance=mypage)
    if request.method == "POST":
        form = PageForm(request.POST, request.FILES or None, instance=mypage)
        if form.is_valid():
              form.save()
              return redirect('page_update', id=id)                  
        else:
            print(form.errors)

    context_dict["form"] = form
    return render(request, template, context_dict)

Form in the template:

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="update" />
</form>

When I save form without image it works fine. But when I upload an image there is always an error:

Exception Type: OSError 
Exception Value: [Errno 22] Invalid argument

Full Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in  get_response
132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
110.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22.                 return view_func(request, *args, **kwargs)
File "C:\mysite\mysite\pages\views.py" in page_update_view
588.                   form.save()
File "C:\Python27\lib\site-packages\django\forms\models.py" in save
459.                              construct=False)
File "C:\Python27\lib\site-packages\django\forms\models.py" in save_instance
105.         instance.save()
File "C:\mysite\mysite\pages\models.py" in save
215.         super(Page, self).save(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save
734. force_update=force_update, update_fields=update_fields)
 File "C:\Python27\lib\site-packages\django\db\models\base.py" in save_base
762. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in _save_table
824.                       for f in non_pks]
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in pre_save
314.             file.save(file.name, file, save=False)
File "C:\Python27\lib\site-packages\django\db\models\fields\files.py" in save
93.             self.name = self.storage.save(name, content, max_length=self.field.max_length)
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in save
63.         name = self._save(name, content)
File "C:\Python27\lib\site-packages\django\core\files\storage.py" in _save
248.                     fd = os.open(full_path, flags, 0o666)

Can anyone help to figure out what's wrong with it. It doesn't work only on Windows, on Linux it goes fine.

You're trying to upload the image to img/ , which is not a valid Windows path (backslash separators). If you want it to work in both Linux and Windows, you could do something like:

import os

def get_image_path(instance, filename):
    return os.path.join("img", filename)

class Page(models.Model):
    ...
    img = models.ImageField(upload_to=get_image_path, blank=True, null=True)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM