title: Upload file to Django with dynamic path
body: <p>I am trying to upload files and organise the directory structure in the media folder.  In specific I want the upload to create subfolders basis one of the values in the model.  The issue I face is that in the view I add information to the instance (in my example code this is the relevant <code>profile</code>).  I would like to use this information for the subfolder, but it does not exist in my model until the save which is after the upload...</p>
  
  <p>What would be the appropriate approach to get the information into <code>Upload</code> so that the subfolder can be created?</p>
  
  <p>Thanks</p>
  
  <p>Model:</p>
  
  <pre><code>class Upload(models.Model):
      file = models.FileField(upload_to="upload/")
      profile = models.ForeignKey(Profile, blank=True, null=True)
  
      def get_upload_to(self, field_attname):
          return 'upload/%d' % self.profile
  </code></pre>
  
  <p>View:</p>
  
  <pre><code>def profile(request, profile_slug):
      profile = Profile.objects.get(slug=profile_slug)
      context_dict['profile'] = profile
      if request.method=="POST":
              for file in request.FILES.getlist('file'):
                      upload = UploadForm(request.POST, request.FILES)
                      if upload.is_valid():
                              newupload = upload.save(commit=False)
                              newupload.profile = profile
                              newupload.save()
      else:
          pass
  
      upload=UploadForm()
      context_dict['form'] = upload
  
      return render(request, 'app/profile.html', context_dict)
  </code></pre>
  
  <p>SOLUTION, thanks to xyres:</p>
  
  <p>Model:</p>
  
  <pre><code>def get_upload_to(instance, filename):
      return 'upload/%s/%s' % (instance.profile, filename)
  
  class Upload(models.Model):
      file = models.FileField(upload_to=get_upload_to)
      profile = models.ForeignKey(Profile, blank=True, null=True)
  </code></pre>
  
  <p>View:</p>
  
  <pre><code>def profile(request, profile_slug):
      profile = Profile.objects.get(slug=profile_slug)
      context_dict['profile'] = profile
      if request.method=="POST":
          upload = UploadForm(request.POST, request.FILES)
          if upload.is_valid():
              for f in request.FILES.getlist('file'):
                  Upload.objects.create(file=f, profile=profile)
          return redirect(reverse('profile')
      else:
          pass
  
      return render(request, 'app/profile.html', context_dict)
  </code></pre>