我正在使用gallery创建Django应用程序。那个画廊有专辑和照片。
照片有专辑的外键
在模板中我发送文件和专辑ID(只有一个人可以添加一些东西到画廊,所以我不必担心这是一个安全漏洞)。我用dropzone的javascript发送这些文件
然后在视图中我使用这样的代码来保存照片:
if 'addphotos' in request.POST:
if ('Album' in request.POST):
ualbum = Album.objects.get(id=request.POST['Album'])
print(ualbum.title)#just checking, this part works
files = [request.FILES.get('dzfile[%d]' % i) for i in range(0, len(request.FILES))]
for ufile in files:
p = Photo.objects.create(album=ualbum, file=ufile)
有些东西不适用于文件。已创建照片对象,但未附加文件。 在./manage.py shell中,我做了类似这样的事情:
>>> from main.models import Photo
>>> from main.models import Album
>>> album = Album.objects.get(id=8)
>>> print (album.title)
teraz zadziała
>>> photos = Photo.objects.filter(album=album)
>>> print(photos)
<QuerySet [<Photo: Photo object>, <Photo: Photo object>, <Photo: Photo object>]>
>>> for photo in photos:
... print(photo.album.title)
...
teraz zadziała
teraz zadziała
teraz zadziała
>>> for photo in photos:
... print(photo.file.url)
...
Traceback (most recent call last):
File "<console>", line 2, in <module>
File "/home/zeko/Pulpit/grh/stronka/s/lib64/python3.4/site-packages/django/db/models/fields/files.py", line 70, in url
self._require_file()
File "/home/zeko/Pulpit/grh/stronka/s/lib64/python3.4/site-packages/django/db/models/fields/files.py", line 47, in _require_file
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'file' attribute has no file associated with it.
为什么会这样?
照片在我的models.py中:
class Photo(models.Model):
album = models.ForeignKey('Album')
file = models.ImageField(upload_to='img/')
我的settings.py中的媒体:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
我在哪里做错了什么?