i need save files, not request.files, saved record.
here's code model record:
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') and view (in case myform model form saves realrecord):
def example(request, record=1, template_name="form.html") foo_obj = foo.objects.get(pk=record) saved_files = {} 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()) so thing fieldfile being used uploadedfile object.
each foo have foofile record name awesome_file , name mediocre_file, matching required fields in realrecord.
the crazy thing is, totally validates. however, problem in resulting record created, both awesome_file , mediocre_file have path in "foo_folder". don't want files in "foo_folder", want them in path specified each field in realrecord.
so guess wondering can fieldfile values coming foofield behave traditional uploadedfile , upload_to , path values of respective fields.
awww... guys! hoping come answer. anyway, able come own solution; not sure if it's optimal 1 works.
i made slight mod foofile stores content_type of uploaded file:
class foofile(models.model): name = models.charfield(max_length=100) file = models.filefield(upload_to='foo_folder') content_type = models.charfield(max_length=254) # max length given rfc 4288 foo = models.foreignkey(foo, related_name='files') and then, in view, create simpleuploadedfile object each foofile record:
from django.core.files.uploadedfile import simpleuploadedfile import os def example(request, record=1, template_name="form.html") foo_obj = foo.objects.get(pk=record) saved_files = {} saved_file in foo_obj.files.all(): saved_files[file.name]=simpleuploadedfile(os.path.basename(saved_file.file.path), saved_file.file.read(), saved_file.content_type) 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())
Comments
Post a Comment