'Edit FileField file contents from Django Admin
I have a situation where I have python scripts that are stored as files that need to be modified from the Admin panel. Currently some of my models can have scripts attached to them:
class Action(PolymorphicModel):
title = models.CharField(max_length=100)
text = BBCodeField('text', blank=True)
action_script = models.FileField(upload_to='action_scripts')
In my Admin panel I can upload a file but I have been asked to make this file editable in-place if the user has the right permissions. I've searched all over for an idiomatic way to do this, and so far I've come up with the following ideas:
- Override the
FileFieldwidget to include an text edit box and save button. This seems very brute forced - Replace
models.FileFieldwith subclass ofmodels.TextField, implement read from file, save to file, but then I lose the upload widget and data still gets stored in DB. This seems dirty because in the database all I'm storing is a filename.FileFieldfeels like the right field type here. - Write a custom
ModelFormthat includesforms.TextField. Handle save to file using thesavemethod. I'm not sure how to accomplish this because I would have to generate a filename on the fly and I don't have a primary key yet. Maybe some sort of UUID?
I'm leaning against door number 3 right now, but I've only been using Django for a week, so I'm not sure this is the right way to go, or even how to do it. Also I would need to have a custom ModelForm for every model that inherits from Action, which violates DRY.
Further complications:
- Not all
Actions need scripts. If the textbox is empty, theFileFieldcan just becomeNull. Actionis subclassed into a handful of derived classes. The editing functionality should extend to each model's Admin panel in a scalable way, like the other fields.
This question seems generic enough that its solution would be useful for those wishing to edit HTML or CSS from the admin, etc, the same as WordPress does. Searching along those lines unfortunately brings up results to do with skinning the admin, which I'm not after. In my situation I'm trying to avoid storing python code in the database for security reasons. The Admin interface is not going to be exposed to the end users so in theory it should be safe, and I get the benefit of caching, compilation and locality (less hits to the DB).
Many thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
