我已经尝试了很多东西来解决这个问题,但我仍然无法解决这个问题。
我无法在模板中正确渲染我的MEDIA图像,但页面源中的网址是正确的绝对路径,但图像仍然无法显示。
models.py
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
import os
class Contact(models.Model):
user = models.OneToOneField(User,null=True)
website = models.URLField(blank=True,null=True)
db = models.ImageField(upload_to=settings.MEDIA_ROOT)
def __unicode__(self) :
return unicode(self.user) or u''
views.py
from django.shortcuts import render
from .models import Contact
from django.contrib.auth.models import User
def user_page(request,user_name):
try :
user = User.objects.get(username=user_name)
except User.DoesNotExists :
return (request,'main.html')
return render(request,'main/user_page.html',{'user':user})
urls.py
from django.conf.urls import url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import views
urlpatterns = [
url(r'^(?P<user_name>\w+)/$',views.user_page , name = 'main_page'),
]
if settings.DEBUG :
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
主/ user_page.html
{% load staticfiles %}
<h1>{{user.username}}</h1>
<img src="{{user.contact.db.url}}" alt="My image"/>
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATIC_DIR = (
os.path.join(PROJECT_DIR,'static'),
)
MEDIA_ROOT =os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
感谢并抱歉英语不好
答案 0 :(得分:0)
alertify.confirm("Are you sure?", function (e) {
if (e) {
alertify.success("Yes");
} else {
alertify.success("No");
}
});
错了。报价表格文件:
FileField.upload_to
将是的本地文件系统路径 附加到您的MEDIA_ROOT设置以确定网址的值 属性。
因此:
db = models.ImageField(upload_to=settings.MEDIA_ROOT)
将上传到MEDIA_ROOT +&#34; foo&#34;。
答案 1 :(得分:0)
尝试这样做:
<强> models.py:强>
class Contact(models.Model):
user = models.OneToOneField(User,null=True)
website = models.URLField(blank=True,null=True)
db = models.ImageField(upload_to=some_folder_here)
def __unicode__(self) :
return unicode(self.user) or u''
def get_db_url(self):
return "{}{}".format(settings.MEDIA_URL, self.db)
<强> views.py:强>
def user_page(request,user_name):
try :
user = User.objects.get(username=user_name)
photo = Contact.objects.filter(user=user)
except User.DoesNotExists :
return (request,'main.html')
context = {
'user': user',
'photo': photo
}
return render(request,'main/user_page.html', context)
<强> HTML:强>
{% load staticfiles %}
<img src="{{ photo.get_db_url }}" alt="My image" />