EADST

Add uploading files feature for Django admin

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
相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
站点统计

本站现有博文258篇,共被浏览416945

本站已经建立1985天!

热门文章
文章归档
回到顶部