I am working on a Django project where users should be able to upload images using Dropzone.js At the moment user images would be saved under mypp/images folder However I would like to save the path of uploaded images dynamically. E.g. /images//image1.jpg Btw I am using django-registraion-redux package (v 1.1) to handle my user registration & login. These are my codes:
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())
Template
<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/'
Right now when I try to upload an image I get the error : AttributeError at /upload-picture/ 'Picture' object has no attribute 'user' any suggestion would be appreciated !
In Models.py:
You have: instance.user.user.username. There's an extra .user there. It should be something like this:
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)
This should work.