I want individual users to be able to upload their files into a single folder (so each user has their own root folder, where they can upload their own files), but I am not sure of the best way to go about implementing this.
I originally planned to use the users email as the their folder name, and all their uploads would be saved in this folder. However, from what I have gathered the only way of retrieving this information is through the request function, and I cannot manage to get an instance of request into the models.py file, and therefore cannot add it to my 'upload_to' directory.
Any other ideas of how to separate users files, or how to get an instance of request in the models file would be greatly appreciated!!
Here is my current model:
def user_directory_path(instance, filename):
return 'user_{0}/{1}'.format(instance.user.id, filename)
class UploadModel(models.Model):
user = models.OneToOneField(User)
file = models.FileField(upload_to=user_directory_path)
And it's associated error:
Exception Value: UploadModel has no user.
I don't recommend you to use user email or any other information that can be updated as folder name because you won't change folder name each time he changes his email or his username. So, use user id that is unique and unchangeable.
Here is a complete example from Django documentation, to access instance information in your models to build path with user id :
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class MyModel(models.Model):
upload = models.FileField(upload_to=user_directory_path)
In this case, it use the user id in the folder name. Of course, your can replaceFileField
with ImageField
.
More information in django docs : FileFields.upload_to
You could maybe separate the folder by their username? You can create a function that would create a folder using the users username like so:
def get_user_image_folder(instance, filename):
return "%s/%s" %(instance.user.username, filename)
and in your model you could easily use the upload_to
and add the function that you just created to it:
class Images(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to=get_user_image_folder,
verbose_name='Image', )
You don't have to use request
in Models, you use instance
instead.
To get this to work I implemented the solution from the docs as suggested by Louis Barranqueiro, whereby the models looks like:
# models.py
def user_directory_path(instance, filename):
return 'user_{0}/{1}'.format(instance.user.id, filename)
class Document(models.Model):
file = models.FileField(upload_to=user_directory_path)
uploaded_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='documents')
But crucially, I also changed my DocumentUploadView class to include a save step, so that the document saves with the user attribute (note also the initial commit=False save step, which is crucial):
# views.py
class DocumentUploadView(View):
def get(self, request):
documents_list = Document.objects.all()
return render(self.request, 'file_upload.html', {'documents': documents_list})
def post(self, request):
form = DocumentForm(self.request.POST, self.request.FILES)
if form.is_valid():
document = form.save(commit=False)
document.user = request.user
document.save()
data = {'is_valid': True, 'name': document.file.name, 'url': document.file.url}
else:
data = {'is_valid': False}
return JsonResponse(data)
Finally my forms.py looks like this:
# forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('file',)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With