怎么调试也调试不好,路径正确但数据库的图片不能正常显示。找了好久 才知道问题在哪,以及解决方案。
bug 原因: 很有可能是路径问题导致的图片不显示。 所以解决方案是 首先更改 settings.py里的设置
在STATICFILES_DIRS 里面添加 上传文件夹地址(media1001,换成你自己的 就可以了)
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') MEDIA_ROOT = 'media1001/' MEDIA_URL = '/media1001/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #os.path.join(BASE_DIR, "media1001"), "media1001" ] 然后其他的地方就不用更改了,直接可以在前端调用了。但是为了更详细些,下面会把其他的一起贴出来 首先是 models #产品 class Product(models.Model): title = models.TextField(u'型号') content = models.ImageField(u'图片',upload_to='uploadImages') price = models. BigIntegerField(u'价格') pub_date = models.DateTimeField(u'时间', auto_now_add=True, editable=True) def __unicode__(self): return self.title 然后是 视图 这里面添加了分页功能 def product(request):#产品 contact_list = Product.objects.all() paginator = Paginator(contact_list, 2) # Show 25 contacts per page page = request.GET.get('page') try: contacts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. contacts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. contacts = paginator.page(paginator.num_pages) return render(request, 'product.html', {'contacts': contacts}) 然后前端调用就可以了 {% for contact in contacts %} {# Each "contact" is a Contact model object. #} <div> <img style="width:100px; height:100px" src="{% static contact.content %}"> {{contact.title}} {{contact.price}} </div> {% endfor %} <div class="pagination"> <span class="step-links"> {% if contacts.has_previous %} <a href="?page={{ contacts.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}. </span> {% if contacts.has_next %} <a href="?page={{ contacts.next_page_number }}">next</a> {% endif %} </span> </div>