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

How to upload multiple images in Django using Dropzone and saving path dynamically ?

我正在开发一个 Django 项目,用户应该可以使用 Dropzone.js 上传图片 目前用户图片将保存在 mypp/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/ 处的 AttributeError 'Picture' 对象没有属性 'user' 任何建议将不胜感激!

在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)

这应该有效。

使用 图片 = models.ImageField(upload_to = "/media/")