通过django向mysql传图片 settings.py MEDIA_ROOT = os.path.join(BASE_DIR, ‘media’).replace(’\’, ‘/’) # 设置静态文件路径为主目录下的media文件夹 MEDIA_URL = ‘/media/’ urls.py from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import include, path urlpatterns = [ path(‘admin/’, admin.site.urls), path(’’,include(‘Product.urls’)) ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ** views.py** from . import models def subswiper(request): if request.method == ‘POST’: # img = request.FILES.get(‘photo’) # user = request.FILES.get(‘photo’).name swiper1 = models.Swiper( photo=request.FILES.get(‘photo’), # 拿到图片 photo_name=request.FILES.get(‘photo’).name # 拿到图片的名字 ) swiper1.save() # 保存图片 return HttpResponse(‘轮播图上传成功!’)
return render(request,‘Product/subswiper.html’) subswiper.html
上传轮播图 {% csrf_token %}
上传轮播图
**models.py** class Swiper(models.Model): photo=models.ImageField(upload_to='swipers') photo_name = models.CharField(max_length=32,primary_key=True) #upload_to='static/swipers/'是指定图片存储的文件夹名称,上传文件之后会自动创建
|