Django server side file selector

Note: This is no longer valid. You can now use the meta.FilePathField that is built into Django like this

fieldName = meta.FilePathField(path='/path/to/files', match='re_string', recursive=True)
I keep coming up with things that I think Django should have built in, but then end up being super easy to implement with just a few lines of code in the model. The TinyMCE editor was a good example of this, and it happened again with what I call a server side file selector. A project I am working on requires the admin user to select a video file to be associated with a message. I don't want users trying to upload very large video files over a HTTP POST, so they are manually uploaded to a directory via FTP. Initially the admin users had to manually type in the file location to a charField, but that just sucks. So I thought "Wouldn't it be great if I could do something like
videoUrl = meta.ServerFileField('/home/user/video')
and Django would automatically create a select field with all the files from that dir as options." After an hour of looking through core.py and formfields.py it dawned on me that I could just do this in the model. So here it is.
from django.core import meta
import os

videoDir = '/home/jay/video'
files = os.listdir(videoDir)
theList = []
for f in files:
	if os.path.isfile(os.path.join(videoDir,f)):
		theList.append(tuple([os.path.join(videoDir,f), f]))
videoChoices = tuple(theList)

class Message(meta.Model):
    def __repr__(self):
        return self.name
    
    title = meta.CharField(maxlength=200)
    video = meta.CharField(maxlength=200, help_text='Select the video', choices=videoChoices ,blank=True)
...
I had forgotten that Django can produce a select field if you just pass the meta.CharField a tuple of choices. No screenshot of this one since Gimp seems to have a hard time taking a screenshot of a HTML Select box





Powered by Django.