from django.db import models #增加
from django.contrib import admin #增加
# Create your models here.
class Item(models.Model):
name = models.CharField(max_length = 250)
description = models.TextField()
class Meta:
ordering = ['name']
def __unicode__(self):
return self.name
@models.permalink #更改
def get_absolute_url(self):
return ('item_detail', None, {'pk':self.id})# object_id 改为pk,是为后面items/url.py,
class Photo(models.Model):
item = models.ForeignKey(Item)
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='photos')
caption = models.CharField(max_length=250, blank=True)
class Meta:
ordering = ['title']
def __unicode__(self):
return self.title
@models.permalink #更改
def get_absolute_url(self):
return ('photo_detail', None, {'pk':self.id})# object_id 改为pk,是为后面items/url.py,
class PhotoInline(admin.StackedInline):
model = Photo
class ItemAdmin(admin.ModelAdmin):
inlines = [PhotoInline]
admin.site.register(Item, ItemAdmin)
admin.site.register(Photo)
2 settings.py增加如下代码
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
3 django 1.7.1请安装pillow
pip install pillow
4 此时,如果按教程操作,点击currently:link会报404错误
Page not found (404)
Request Method: | GET |
---|---|
Request URL: | http://127.0.0.1:8000/media/photos/2.jpg |
Using the URLconf defined in gallery.urls
, Django tried these URL patterns, in this order:
- ^admin/
The current URL, media/photos/2.jpg
, didn't match any of these.
urls.py源代码改为如下:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gallery.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
完整代码的运行截图如下