Add uploading files feature for Django admin
作者:XD / 发表: 2020年5月8日 22:27 / 更新: 2020年5月8日 22:37 / 编程笔记 / 阅读量:2594
I was writing an article to introduce my latest research work. However, my blog was not able to upload and share PDF files.
Therefore, I added uploading files feature for Django admin. Here are the steps.
1. Add the class in models.py
class File(models.Model):
file_title = models.CharField(max_length=50, verbose_name=u'File Title', default='')
file_detail = models.CharField(max_length=200, verbose_name=u'File Detail', default='')
file_path = models.FileField(max_length=100, verbose_name=u"File", default='',
upload_to='upload/%Y/%m')
class Meta:
verbose_name = u'Site File'
verbose_name_plural = verbose_name
def __str__(self):
return self.file_title
2. Add the class in admin.py
from .models import File
class FileAdmin(admin.ModelAdmin):
list_display = ('file_title', 'file_detail', 'file_url', 'file_data')
readonly_fields = ('file_data', 'file_url',)
def file_url(self, obj):
return mark_safe(u'Copy URL by Clicking right button.' % obj.file_path.url)
def file_data(self, obj):
file = mark_safe(u'Filename%s' % obj.file_path.url)
return file
file_data.short_description = u'File'
file_url.short_description = u'File URL'
admin.site.register(File, FileAdmin)
3. Migrate database
python manage.py makemigrations
python manage.py migrate
相关标签