Set the current user to the model when posting a form

23 views Asked by At

I am trying to add the request user to a model.

def fileupload(request):
files = Download.objects
if request.method == "POST" :
    form = DownloadForm(request.POST, request.FILES)
    if form.is_valid():
        author = request.user
        savefile = form.save()
        savefile.save()

My models is :

class Download(models.Model):
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE, related_name="filedownload")
upload = models.FileField(upload_to='uploads/')

But the author is not updating, any clue ?

1

There are 1 answers

2
NS0 On BEST ANSWER

You need to add author to your form object. The exact way to do that depends on your form class -- so maybe include that in your post.

Try something like this:

def fileupload(request):
    files = Download.objects
    if request.method == "POST" :
        form = DownloadForm(request.POST, request.FILES)
        if form.is_valid():
            form.author = request.user  # <--- changed to `form.author`
            savefile = form.save()
            savefile.save()