【问题标题】:django - any image upload and display method using Ajax?django - 任何使用 Ajax 的图像上传和显示方法?
【发布时间】:2011-08-11 05:41:30
【问题描述】:

在我的 django 应用程序中,我使用 ImageKit 来调整加载到服务器的图像的大小。

models.py

class Pictures(ImageModel):
    user = models.ForeignKey(User)
    original_image = models.ImageField(upload_to='userpx')

    class IKOptions:
        # This inner class is where we define the ImageKit options for the model
        spec_module = 'userprofile.specs'
        cache_dir = 'modpics'
        image_field = 'original_image'
        save_count_as = 'num_views'
    def __unicode__(self):
        return u'%s' % (self.original_image)

forms.py

class PicturesForm(forms.Form): 
   image = forms.ImageField()

template.html

<img src="{{ p.thumbnail_image.url }}" >

<form action="" method="POST" class="cmxform" enctype="multipart/form-data">
{% csrf_token %}
{{aform.as_p}}
<input type="submit" value="submit" name="picture_button" />        
</form>

views.py

   if 'picture_button' in request.POST:
        aform = PicturesForm(request.POST, request.FILES)
        if aform.is_valid():
            # an UploadedFile object
            a_user = User.objects.get(id=request.user.id)

            #Check if image entry exists 
            try:
                p = Pictures.objects.get(user=request.user.id)

            except Pictures.DoesNotExist: 
                picture = Pictures.objects.create(user = a_user)
                image_file = request.FILES['image']
                picture.original_image.save(image_file.name, image_file)

                #show picture and form
                p = Pictures.objects.get(user=request.user.id)
                aform = PicturesForm()

            else:
                p.delete()
                picture = Pictures.objects.create(user = a_user)
                image_file = request.FILES['image']
                picture.original_image.save(image_file.name, image_file)

                #show image and form
                p = Pictures.objects.get(user=request.user.id)
                aform = PicturesForm()


    else:
        p = Pictures.objects.get(user=request.user.id)
        aform = PicturesForm()

Using some Ajax method 我怎样才能消除template.html 中的提交按钮,这样当用户从他/她的机器中选择图像时,图像会自动上传到服务器然后显示回服务器?

感谢您的帮助!

【问题讨论】:

    标签: jquery ajax django django-forms django-imagekit


    【解决方案1】:

    我可能会使用:

    http://jquery.malsup.com/form/

    使用 ajax 提交表单,然后通过成功回调将图像加载到 dom 中。

    【讨论】:

    • 感谢您的链接!我会调查的。有什么真实的例子吗?
    猜你喜欢
    • 2019-10-29
    • 2019-10-22
    • 2018-02-06
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    相关资源
    最近更新 更多