我正在开发一个 Django 项目,用户应该能够使用Dropzone.js上传图像目前用户图像将保存在 mypp/images 文件夹下但是我想动态保存上传图像的路径。例如 /images//image1.jpg 顺便说一句,我正在使用django-registraion-redux包(v 1.1)来处理我的用户注册和登录。这些是我的代码:
模型.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,)
格式.py
class PictureForm(forms.ModelForm):
class Meta:
model = Picture
fields = ('image',)
视图.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>
网址.py
urlpatterns = [url(r'^upload-picture/', 'myapp.views.upload_picture', name='upload_picture'),]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
设置.py
MEDIA_ROOT = 'C:/Users/mhsha/Desktop/board'
MEDIA_URL = '/media/'
现在,当我尝试上传图像时,出现错误:/upload-picture/'Picture' 对象的 AttributeError 没有属性'user' 任何建议将不胜感激!