Django Python uploading a `FileField` to a specific folder

How can I use the django FileField to upload the file to the specified folder directly without going through the admin panel or using the form for normal user?

The Django FileField itself doesn’t upload anything. It’s a reference to a file accessible to the server (uploaded or otherwise). Other processes that put files on the server can create FileFields so that Django has a way of working with them.

What, precisely, are you trying to accomplish?

I need to programmatically push each file from the local file system into a Django model.

You’ve got a couple different choices:

  • Write a script (Python, bash, whatever) to post each file to an appropriate view.

  • Copy the files to the server, then write a management command to “import” (and I’m using that term loosely) those files into your Django app.

There are probably other options, but all the ones I can think of are just basic variations on one of these two.

1 Like

But It takes time to do that!!

Can I use the following coding?

class DemoMCall(models.Model):
rid = models.PositiveBigIntegerField(primary_key=True)
info_agent = models.CharField(max_length=200, blank=True, null=True)
audio_file = models.FileField( upload_to = user_directory_path )

def user_directory_path(instance):
   # file will be uploaded to MEDIA_ROOT
   return 'rec{0}_{1}'.format(instance.DemoMCall.rid, instance.DemoMCall.info_agent)

True. So you need to decide which is going to be more time / cost effective. Write the script to import the files, or have someone manually enter them.

What do you expect that code to do for you?
(Hint: It’s not going to do anything to get the information about the files into the file fields in the instances of your model.)

You yourself wrote:

So you’ve got the idea. You need to programmatically push each file - you’ve got to write something that does that. It’s a “push” from the client, not a “pull” from the server.