1

The goal is to dynamically update upload_to such that user uploaded files are stored in a directory location that depends on the user. There are several examples of this online, but none using ModelForm. See the code snippets for the two problems, one is that I am getting an empty string for the instance.user value, and when I try and fix that, the form is not valid.

# models.py

def get_file_path( instance, filename ):
    # make the filepath include the signed in username
    print "inst: %s" % instance.__dict__.keys()
    print "inst:user:%s" % instance.user   # <-- This is empty string!!
    print "file: %s" % filename
    return "%s/myapp/%s/%s" % ( settings.MEDIA_ROOT, instance.user, filename )

class trimrcUpload(models.Model):
    user = models.CharField( max_length = 20 )
    inputFile = models.FileField( upload_to = get_file_path )


# forms. py

class trimrcUploadForm(ModelForm):

    class Meta:
        model = trimrcUpload
        exclude = ( 'resultFile', 'numTimesProcessed' )

# views.py

def myapp_upload( request, username, template_name="myapp/myapptemplate.html" ):

    dummy = trimrcUpload( user=username )
    if request.POST:
        form = trimrcUploadForm( request.POST, request.FILES, instance=dummy )
        if form.is_valid():
            success = form.save()
            success.save()

    # form is not valid, user is field is "required"
    # the user field is not displayed in the template by design,
    # it is to be populated by the view (above).

# http://docs.djangoproject.com/en/1.0/topics/forms/modelforms/
# about halfway down there is a "Note" section describing the use of dummy.

2 Answers 2

1

I would imagine your problem comes from trying to populate the user attribute of your model with a username. If the upload form will always be used by a logged in user, you can use this instead:

dummy = trimrcUpload( user=request.user )

Otherwise, if you still want to pass in the username like you do now, you can try something like:

try:
    user = User.objects.get(username=username)
    dummy = trimrcUpload( user=user )
except User.DoesNotExist:
    # Probably have to set some kind of form error

I would recommend going with the first option which would allow you to not have to pass username to the view.

Sign up to request clarification or add additional context in comments.

1 Comment

But username is a valid string. OMG. I don't know why, but its completely working now. I better flag this as answered.
0

The original code in the question actually works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.