Question

I would like my file upload to be renamed before being saved to disk. The logic I want to use to set the name would be contained in the view.

I want to pass my getname variable from my view into my model class before saving. Here is my broken code.

View:

getname = 'foo' #I want this string to get passed into upload_to in the model

form = DocumentForm(request.POST, request.FILES)

if form.is_valid(): 

    newdoc = Document()
    newdoc.filename = getname #This line doesn't work
    newdoc.docfile = request.FILES['docfile']
    newdoc.save()

Model:

class Document(models.Model):

    filename = ''
    docfile = models.FileField(upload_to=filename)

I have read through several of these links but whenever I touch my code I break it.

http://www.malloc.co/django/django-rename-a-file-uploaded-by-a-user-before-saving/ http://catherinetenajeros.blogspot.com/2013/03/rename-path-when-imagefile-upload.html

Edit: I've revised the code to help make my question more clear.

Was it helpful?

Solution

I think this is what you want, assuming getname is entered into the form in your view:

First, your model:

def upload_function(instance, filename):
    getname = instance.name
    # Add other filename logic here
    return customfilename # Return the end filename where you want it saved.

class Document(models.Model):

    name = models.CharField(max_length=25)
    docfile = models.FileField(upload_to=upload_function) # The upload_to argument sends it to your upload function.

In this case, you're creating your own upload_to function (here called upload_function). You can read about that here. When running this function, it will pass the instance as a first argument, so you can access its properties. Thus, we'll access its name when creating our filename. Further explanation here.

Now your view:

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import DocumentForm
from .models import Document

def upload_file(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            instance = Document(docfile=request.FILES['file'])
            instance.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = DocumentForm()
    return render(request, 'upload.html', {'form': form})

This view checks your form to make sure it's valid, then saves the uploaded file. Assuming your DocumentForm has a field for name, this will be assigned first, which means your function for upload_to will be able to access it. The sample language for this view came from the Django docs here.

Please let me know if this works.

OTHER TIPS

If i understand correctly , you're looking for something like this ,

newdoc.instance.your_attribute = getname
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top