2009年7月29日 星期三

欄位用ImageField的儲存與顯示

1.model.py欄位的設定
image1 = models.ImageField('圖1.',upload_to ='tcimage/',blank=True,null=True)
image2 = models.ImageField('圖2.',upload_to ='tcimage/',blank=True,null=True)

2.setting.py的設定
MEDIA_ROOT = 'C:/python25/opentc/media/'

3.問題
admin中的網址顯示錯誤

解決方案在setting.py中設定MEDIA_URL
MEDIA_URL = '/'

4.在Template的顯示

The ImageField and FileField URLs are relative to MEDIA_URL
It's important to skip the leading slash, and add an slash to the end of
the path Attribute.
example:

image = models.Imagefield(path="images/")

In the Template use {{MEDIA_URL}}{{image.url}}


參考資料如下:

Using a FileField or an ImageField (see below) in a model takes a few steps:

  1. In your settings file, you'll need to define MEDIA_ROOT as the full path to a directory where you'd like Django to store uploaded files. (For performance, these files are not stored in the database.) Define MEDIA_URL as the base public URL of that directory. Make sure that this directory is writable by the Web server's user account.
  2. Add the FileField or ImageField to your model, making sure to define the upload_to option to tell Django to which subdirectory of MEDIA_ROOT it should upload files.
  3. All that will be stored in your database is a path to the file (relative to MEDIA_ROOT). You'll most likely want to use the convenience url function provided by Django. For example, if your ImageField is called mug_shot, you can get the absolute URL to your image in a template with {{ object.mug_shot.url }}.

For example, say your MEDIA_ROOT is set to '/home/media', and upload_to is set to 'photos/%Y/%m/%d'. The '%Y/%m/%d' part of upload_to is strftime formatting; '%Y' is the four-digit year, '%m' is the two-digit month and '%d' is the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in the directory /home/media/photos/2007/01/15.

If you want to retrieve the upload file's on-disk filename, or a URL that refers to that file, or the file's size, you can use the name, url and size attributes; see Managing files.

Note that whenever you deal with uploaded files, you should pay close attention to where you're uploading them and what type of files they are, to avoid security holes. Validate all uploaded files so that you're sure the files are what you think they are. For example, if you blindly let somebody upload files, without validation, to a directory that's within your Web server's document root, then somebody could upload a CGI or PHP script and execute that script by visiting its URL on your site. Don't allow that.

沒有留言:

張貼留言