Django图像上传总是失败,表单永远不会有效

时间:2015-05-09 09:40:49

标签: python django image forms

上传到默认django db的简单图像永远不会完成。该错误似乎表明图像字段出现问题,就像我的views.py打印form.errors,它返回

  • image
  • 此字段是必填字段。
  • 这是我的代码,我只上传了我认为可能影响它的内容。

    models.py

    class Image(models.Model):
         name = models.CharField(max_length=128, unique=True)
         image = models.ImageField(upload_to="user_images")
         slug = models.SlugField(unique=True)
    
        def save(self, *args, **kwargs):
           self.slug = slugify(self.name)
           super(Image, self).save(*args, **kwargs)
    
       def __unicode__(self):
           return self.name
    

    forms.py

    from django import forms
    from shareIt.models import Image
    
    class ImageForm(forms.ModelForm):
        name = forms.CharField(max_length=128, help_text="Please enter an image name")
        image = forms.ImageField()
        slug = forms.CharField(widget=forms.HiddenInput(), required=False)
    
    class Meta:
        model = Image
        fields = ('name', 'image')
    

    views.py

    def uploadImage(request):
    
    if request.method== 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(commit=True)
            return images(request)
        else:
            print form.errors
    else:
        form = ImageForm()
    
    contextdict = {"form": form}
    return render(request, 'uploadImage.html', contextdict)
    

    uploadImage.html

    <html>
    <form id="upload" action="/share/images/upload" method="post">
        {% csrf_token %}
        {{ form.as_p }}
    
    <input type="submit" name="submit", value="upload image" />
    </form>
    

    2 个答案:

    答案 0 :(得分:8)

    enctype属性添加到<form>代码:

    <form id="upload" action="/share/images/upload" enctype="multipart/form-data" method="post">
    

    答案 1 :(得分:0)

    使用模型表单时,无需键入:

    name = forms.CharField(max_length=128, help_text="Please enter an image name")
    image = forms.ImageField()
    slug = forms.CharField(widget=forms.HiddenInput(), required=False)
    

    您的模型中已有此功能。你只需要这个:

    class ImageForm(forms.ModelForm):
        class Meta:
            model = Image
            fields = ('name', 'image')