[英]Image upload through admin in Django
I want to be able to upload images through the admin in Django. 我希望能够通过Django中的管理员上传图像。 But I am having some difficulty
但是我有些困难
project structure: 项目结构:
/Proj
/Proj
/static
/img
/albums
/album1
img1
/album2
img2
Album class: 专辑类别:
class Album(models.Model):
title = models.CharField(max_length = 60)
def __unicode__(self):
return self.title
Image class: 图片类别:
class Image(models.Model):
title = models.CharField(max_length = 60, blank = True, null = True)
image = models.FileField(upload_to = get_upload_file_name) <-- !!!!
tags = models.ManyToManyField(Tag, blank = True)
albums = models.ForeignKey(Album)
width = models.IntegerField(blank = True, null = True)
height = models.IntegerField(blank = True, null = True)
created = models.DateTimeField(auto_now_add=True)
I THINK my image = models.FileField(upload_to = get_upload_file_name)
uses the get_upload_file_name
method to place the image in the correct album. 我认为我的
image = models.FileField(upload_to = get_upload_file_name)
使用get_upload_file_name
方法将图片放置在正确的相册中。 This is done through appending to my MEDIA_ROOT
which is MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
这是通过追加到我做
MEDIA_ROOT
这是MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
So the get_upload_file_name
method is supposed to do so. 因此,应该使用
get_upload_file_name
方法。 But I am not sure how to so. 但是我不确定该怎么做。
I think before I can upload I need to create an album first so then I can decide which album the image will go in. A bit lost at this point. 我认为在上传之前,我需要先创建一个相册,然后才能确定该图像将插入哪个相册。 Not sure if my
Image
or Album
class is even complete. 不知道我的
Image
或Album
课程是否完整。 Thanks for the help!! 谢谢您的帮助!!
The function you pass into upload_to
must have the form: 您传递给
upload_to
的函数必须具有以下形式:
def get_upload_file_name(instance, filename):
new_file_path_and_name = os.path.join(BASE_DIR, 'static', 'test.txt')
return new_file_path_and_name
instance
is the instance of the Image
model you're about to save. instance
是您要保存的Image
模型的实例。 That means it has access to all of the other fields that have been populated. 这意味着它可以访问已填充的所有其他字段。
filename
is the original name of the file that was uploaded. filename
是已上传文件的原始名称。 You may choose to use filename
or simply return another path + name of your choice. 您可以选择使用
filename
或简单地返回您选择的其他路径和名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.