How can I add dynamic field in the model in django?
I'm using django to create a applic开发者_JS百科ation download site. I try to write a model, that the admin can add the different download content dynamically in the admin page. For example I have a software named foobar, it have 3 different version: 1.1, 1.2, 1.3. I would like the user can admin the model by using an add button to add the download link with a download version. But I don't know how to do this in django.
Set up your models to have a main model and ancillary models that have foreign keys to the main model:
class DownloadItem(models.Model):
name = models.CharField( etc etc)
... other attributes here ...
class DownloadItemFile(models.Model):
parent = models.ForeignKey('DownloadItem', related_name="versions")
version = models.CharField( etc etc)
file = models.FileField(upload='path/to/uploaddir/')
then, when you have an instance of your DownloadItem model, you can get hold of your various file versions with:
mydownloaditem.versions.all()
To be able to add files via the Admin, you will need to use an inline. In your admin.py for the app in question, you'll need to add something like:
class DownloadItemFileInline(admin.TabularInline):
model = DownloadItemFile
class DownloadItemAdminOptions(admin.ModelAdmin):
inlines = [ DownloadItemFileInline, ]
...other admin options here...
admin.site.register(DownloadItem, DownloadItem AdminOptions)
精彩评论