django 附件添加到数据库

1.使用ImageField首先要安装Pillow

pip install pillow

2.建立数据库

1 class Test(models.Model):
2   name = models.CharField(max_length=50)
3   image = models.ImageField(upload_to='logo')
4   def __str__(self):
5     return self.name

3.初始化数据库

1 python manage.py makemigrations  
2 python manage.py migrate

4.setting设置
       MEDIA_URL = '/media/'
  MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

 TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',#### add here
            ],
        },
    },
]

扫描二维码关注公众号,回复: 1584644 查看本文章

5.views.py

def upload(request):

  if request.method == 'POST':
    file = request.FILES.get('img',None)
    name = request.POST.get('img')
    print(name)

   models.Test.objects.create(name=1,image=file)
img = models.Test.objects.all()
return render(request, 'upload.html',{'img':img})

6.urls添加
from django.conf import settings
from django.conf.urls.static import static
。。。。
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

7.html 这样能显示完全
{% for i in img %}
<img src="{{ MEDIA_URL }}{{ i.image }}">
{% endfor %}

添加文件:
<form action="/upload/" method="post" enctype="multipart/form-data">
<input type="file" name="img">上传文件</input>
</form>


 
 

猜你喜欢

转载自www.cnblogs.com/guowenshuang/p/9179145.html