Django | 使用表单上传图片时出现对象没有'cleaned_data'属性的错误

0 投票
1 回答
778 浏览
提问于 2025-04-18 15:51

我想把一张图片上传到数据库里,但看了很多教程后,这段代码还是不行,因为在打印出表单错误信息后出现了这个错误:

**AttributeError at /upload**
'ImageUploadForm' object has no attribute 'cleaned_data'

这是我的代码:
models.py:

class room_type(models.Model):
    id = models.IntegerField(primary_key = True)
    code = models.CharField(max_length = 40)
    name = models.CharField(max_length= 40 )
    title = models.CharField(max_length = 40)
    english_title = models.CharField(max_length=40)
    capacity = models.IntegerField()
    extra_capacity = models.IntegerField()
    description = models.CharField(max_length=255)
    today_price = models.IntegerField()

    class Meta:
        db_table = 'room_types'
    def __unicode__(self):
        return u'%d' % (self.id)

class attachment(models.Model):

    id = models.IntegerField(primary_key = True)
    image = models.ImageField(upload_to="/home/iman/Desktop/code/hotel/rooms/attachments")

    #foreign key : a room has many images
    rt_id = models.ForeignKey(room_type)
    class Meta:
        db_table = 'attachments'
    def __unicode__(self):
        return u'%d' % (self.id)

forms.py:

  class ImageUploadForm(forms.Form):
        image = forms.ImageField()
        class Meta:
        model = attachment
        fields= ['image']

views.py:

def upload(request):
    if request.method == 'POST':
        print"##########"
        form = ImageUploadForm(request.POST,request.FILES)
        if form.is_valid():
            new_attachment = attachment()
            new_attachment.image= form.cleaned_data['image']
            new_attachment.id = 1
            new_attachment.rt_id = 1
            new_attachment.save()
            print "))))))))"
            #return HttpResponse('image upload success')
        else:
            print form.is_valid() 
            print form.errors
            form = ImageUploadForm()
    return render(request,'index.html') 

index.html :

<div id="dialog" title="آپلود فایل">
            <form action="{% url 'upload' %}" class="dropzone" enctype="multipart/form-data"  id="my-awesome-dropzone" method="post"  >{% csrf_token %}
                  <input id="id_image" type="file" class="" name="image">
                  <input type="submit" value="Submit" />
            </form>
        </div>


> full traceback :  Environment:
> 
> 
> Request Method: POST Request URL: http://localhost:8000/upload
> 
> Django Version: 1.6.5 Python Version: 2.7.3 Installed Applications:
> ('django.contrib.admin',  'django.contrib.auth', 
> 'django.contrib.contenttypes',  'django.contrib.sessions', 
> 'django.contrib.messages',  'django.contrib.staticfiles',  'rooms')
> Installed Middleware:
> ('django.contrib.sessions.middleware.SessionMiddleware', 
> 'django.middleware.common.CommonMiddleware', 
> 'django.middleware.csrf.CsrfViewMiddleware', 
> 'django.contrib.auth.middleware.AuthenticationMiddleware', 
> 'django.contrib.messages.middleware.MessageMiddleware', 
> 'django.middleware.clickjacking.XFrameOptionsMiddleware')
> 
> 
> Traceback: File
> "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"
> in get_response
>   112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/iman/Desktop/code/hotel/rooms/views.py" in upload
>   147.             print form.cleaned_data['image']
> 
> Exception Type: AttributeError at /upload Exception Value:
> 'ImageUploadForm' object has no attribute 'cleaned_data'

1 个回答

1

试着去掉

class Meta:
    model = attachment

撰写回答