Note that there are some explanatory texts on larger screens.

plurals
  1. POCopying files from a saved FileField to an UploadedFile in Django
    primarykey
    data
    text
    <p>I need to save files, not from request.FILES, but from another saved record.</p> <p>Here's the code for the model record:</p> <pre><code>class Foo(models.Model) slug = models.SlugField() class FooFile(models.Model): name = models.CharField(max_length=100) file = models.FileField(upload_to='foo_folder') foo = models.ForeignKey(Foo, related_name='files') class RealRecord(models.Model): slug = models.SlugField() awesome_file=models.FileField(upload_to='awesome') mediocre_file=models.FileField(upload_to='mediocre') </code></pre> <p>And the view (in this case <code>MyForm</code> is a model form that saves to RealRecord):</p> <pre><code>def example(request, record=1, template_name="form.html") foo_obj = Foo.objects.get(pk=record) SAVED_FILES = {} for file in foo_obj.files.all(): SAVED_FILES[file.name]=file.file if request.method == 'POST': form = MyForm(data=request.POST, files=SAVED_FILES) if form.is_valid(): form.save() # rest of view else: form = MyForm() return render(request, template_name, locals()) </code></pre> <p>So the thing is basically a <code>FieldFile</code> is being used as an <code>UploadedFile</code> object. </p> <p>Each <code>Foo</code> will have a <code>FooFile</code> record with the name <code>awesome_file</code> and another with the name <code>mediocre_file</code>, matching up with the required fields in <code>RealRecord</code>.</p> <p>The crazy thing is, this totally validates. <em>However</em>, the problem is that in the resulting record that is created, both awesome_file and mediocre_file have their path in "foo_folder". But I don't want the files in "foo_folder", I want them to be in the path that I specified for each field in <code>RealRecord</code>.</p> <p>So I guess I am wondering what I can do to the <code>FieldFile</code> values coming from <code>FooField</code> so that they behave like a traditional UploadedFile and get the <code>upload_to</code> and <code>path</code> values of their respective fields.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload