这个是项目settings里边的设置
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static').replace('\\', '/'),)
MEDIA_ROOT = os.path.join(BASE_DIR,'polls').replace('\\','/')
MEDIA_URL='/polls/'
然后是model里边的代码,主要定义了ImageField
from django.db import models
class Yangyang(models.Model):
record_date = models.DateTimeField("time")
record_img = models.ImageField(upload_to='img',null=True,blank=True)
recorder= models.CharField(max_length=200)
def __unicode__(self):
return self.recorder
然后是view,主要是detail的。
from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from .models import Yangyang
# Create your views here.
def index(request):
latest_question_list = Yangyang.objects.all()
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
try:
question = Yangyang.objects.get(pk=question_id)
except Yangyang.DoesNotExist:
raise Http404("Question does not exist")
return render_to_response( 'polls/detail.html', {'question': question})
好吧,detail的代码是相当简单的
<img src="{{question.record_img.url}}">
polls 的url配置
<p>from django.conf.urls import url,patterns
from django.conf import settings
from django.conf.urls.static import static</p><p>from . import views</p><p>urlpatterns = [
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
#url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
#url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),</p><p>]</p><p>urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)</p>
开始以为这样就行了,但是每次方位都是图片无法现实的图标,路径看上去也没问题
后来发现最后一句的位置不对。
要放到网站下边的urls
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
最后直接访问:
http://127.0.0.1:8000/polls/4/ 就可以了