Accessing the model instance in a ModelForm's widget

I recently integrated Django Sendfile with a website to provide downloads that required authentication (even knowing the location of an authentication requiring file in the static directory will not allow you to download it thanks to some Apache conf magic).

That was all well and good, but a result was that it was no longer possible to download those files through the admin interface using the default Django file input widget. I figured out that if I could access the current model instance in the FileInput's render I would be able to create a working download link. After a few failed attempts and a lot of Googling I created a custom FileInput widget that could do just that. To do so, I created a ModelForm that looked something like this:

class DummyForm(forms.ModelForm):
    # form code here
    def __init__(self, *args, **kwargs):
        super(DummyForm, self).__init__(*args, **kwargs)
        if hasattr(self, 'instance'):
            self.fields['example_field'].widget.instance = self.instance

Then in the render it's possible to access self.instance (you should check if self has the attribute instance because inputs associated with unsaved models will not).

Comments