Skip to content Skip to sidebar Skip to footer

How To Retrieve Current Logged In User For Dynamic File Name Use In Model

I'm trying to set the current 'upload_to=' directory equal to the current logged-in user's username so that each file uploaded is saved into the user's own directory. I have tried

Solution 1:

Answer : The Django documentation does not specify a user needing to be added to the model - though it does expect one.

When it was done the model looked like this:

defuser_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>return'uploads/{0}/{1}'.format(instance.user.username, filename)


classUploadReports(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    xls = models.FileField(upload_to=user_directory_path)

If you add the user here then DO NOT FORGET to add the user to the field of the form as such:

classDocumentForm(forms.ModelForm):
    classMeta:
        model = UploadReportsfields= ('xls', 'user')

Once you add the field to the form there becomes a new field in the template form with the list of possible users. As most people probably don't, I didn't want the form to include the user. Therefore, as ilja stated, you must exclude the form as such:

classDocumentForm(forms.ModelForm):
    classMeta:
        model = UploadReports
        fields = ('xls', 'user')
        exclude = ('user', ) # make sure thisis a tuple

Once the form is excluded it will go back to throwing the error that the user does not exist. So you need to add the user in the post method of theviews.py as such:

classFileUploadView(View):
    form_class = DocumentForm
    success_url = reverse_lazy('home')
    template_name = 'file_upload.html'defget(self, request, *args, **kwargs):
        upload_form = self.form_class()
        return render(request, self.template_name, {'upload_form': upload_form})

    defpost(self, request, *args, **kwargs):
        upload_form = self.form_class(request.POST, request.FILES)
        if upload_form.is_valid():
            form_done = upload_form.save(commit=False) # save the form but don't commit
            form_done.user = self.request.user # request the user
            form_done.save() # finish saving the formreturn redirect(self.success_url)
        else:
            return render(request, self.template_name, {'upload_form': upload_form})

It is not an easy task but it is rewarding when it is done!

Post a Comment for "How To Retrieve Current Logged In User For Dynamic File Name Use In Model"