如何使用Dropzone在Django中上传多个图像并动态保存路径?

时间:2016-04-11 20:21:01

标签: django django-models dropzone.js django-registration django-uploads

我正在开发一个Django项目,用户应该可以使用Dropzone.js上传图像。目前用户图像将保存在mypp / images文件夹下 但是我想动态保存上传图像的路径。 例如。 /images//image1.jpg 顺便说一句,我正在使用django-registraion-redux包(v 1.1)来处理我的用户注册和登录。 这些是我的代码:

models.py

from django.db import models
from django.contrib.auth.models import User

get_user_image_folder(instance, filename):
return "%s/%s" % (instance.user.user.username, filename)

class Picture(models.Model):
user = models.ForeignKey(User, null=True)
image = models.ImageField(upload_to=get_user_image_folder,)

foms.py

class PictureForm(forms.ModelForm):
class Meta:
    model = Picture
    fields = ('image',)

views.py

def upload_picture(request):
if request.method == 'POST':
    form = PictureForm(request.POST, request.FILES)

    if form.is_valid():
        picture = form.save()
else:
    form = PictureForm()
return render(request, "upload_picture.html", locals())

模板

  <body>
    <form action="{% url 'upload_picture' %}" class="dropzone" id="myDropzone" method='POST' enctype="multipart/form-data">
        {% csrf_token %}

        <div class="fallback">
            <input name="file" type="file" multiple />
        </div>
    </form>

    <script src="{% static 'dropzone/dropzone.js' %}"></script>
    <script type="text/javascript">
        Dropzone.options.myDropzone ={
            paramName: "image", // name of input
            autoProcessQueue : true,
            parallelUploads: 1,

            init :  function (){
                this.on( "success", function( file, responseText){
                    // event launched at the end of uploading images queued
                    console.log( responseText );
                });
            }
        };
    </script>
</body>

urls.py

urlpatterns = [url(r'^upload-picture/', 'myapp.views.upload_picture', name='upload_picture'),]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

MEDIA_ROOT = 'C:/Users/mhsha/Desktop/board'
MEDIA_URL = '/media/'

现在当我尝试上传图片时,我收到错误消息: / upload-picture /'Picture'对象的AttributeError没有属性'user' 任何建议将不胜感激!

2 个答案:

答案 0 :(得分:1)

在Models.py中:

您拥有:instance.user.user.username。那里有一个额外的.user。它应该是这样的:

def get_user_image_folder(instance, filename):
return 'images/{0}/{1}'.format(instance.user.username, filename)

class Picture(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to = get_user_image_folder)

这应该有用。

答案 1 :(得分:1)

use image = models.ImageField(upload_to = "/media/")