Django Upload image, ImageField

Source: Internet
Author: User

Today, when I look at Django, suddenly found that the model has a ImageField, originally thought Django model is just an ORM framework, did not think even upload images to the server can be done, so combined with examples to try. ImageField need PIL support, so PIL this library need to install first.


First create two model:

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, {' object_id ': self.id}) 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, {' object_id ': self.id})    class Photoinline (admin. Stackedinline):    model = Photo    class itemadmin (admin. Modeladmin):    inlines = [Photoinline]        

And then join in the settings.py.Media_root:

Media_root = '/var/www/gallery/media/'
Since I ran with Apache, I need to be aware of directory permissions.

Over here

upload_to= ' photos ' means that the uploaded file will be stored under $media_root/photos/, that is, placed under/var/www/gallery/media/photos/.

After a syncdb, open the admin page, see just built model, add a piece of data, upload pictures, success, Django is really powerful!

Then modify the modified interface of the record that you just added, you can see the hyperlink of the image just uploaded:



Click the image of the hyperlink, but show 404 Not Found, this is strange, on the server clearly already have this file, and the database is added correctly, how to read it back.

There is a strange place here, open the image URL is: http://10.40.3.164:8090/admin/gallery/item/1/photos/github-logo.png/

The value of the href inside the hyperlink is: Photos/github-logo.png, this has the problem ah, the picture should be relatively independent, and do not say here load not to picture, if real use, use this URL definitely wrong.


Well, look at the source code of ImageField.

In the django/db/models/fields/files.py, there are:

Class ImageField (Filefield):
ImageField itself has nothing to do with URL-related things, continue to look at its parent class: Filefield

Class Filefield (Field):    # The class to wrap instance attributes in. Accessing the file object off    # The instance would always return a instance of Attr_class.    Attr_class = Fieldfile

There is an attribute in Filefield Attr_class here that the attributes are all from the class configured here. Then let's continue to look at the Fieldfile class:

Class Fieldfile (File):    def _get_url (self):        self._require_file ()        return Self.storage.url (self.name)    URL = property (_get_url)

Sure enough there is a property called URL, but this property is returned by the Storage.url method. Because it is the file, it is probably filestorage, look at it first.

There is a Filesystemstorage class in django/core/files/storage.py, which has a URL method:

    def url (self, name):        if Self.base_url are None:            raise ValueError ("This file is not accessible via a URL.")        Return Urljoin (Self.base_url, Filepath_to_uri (name))

Here is more clearly, the URL is composed of Self.base_url plus a file of filename, where the value of Self.base_url is determined by media_url This configuration option, and then see Django/conf/global_ setting.py file, the Media_url default is an empty string.

Add Media_url to this configuration option in the settings.py of our project:

Media_url= '/media/'

After restarting Apache, open the modified page of that record again, and see the href attribute of the hyperlink changed to /media/photos/github-logo.png by Firebug.

Click on the hyperlink, the request is the Http://10.40.3.164:8090/media/photos/github-logo.png page, OK this is the href attribute is different beginning with "/".

However, the error is still displayed, but the problem is obvious, and as with setting up a static file, you need to add something to the urls.py of the project:

Urlpatterns + = static (settings. Media_url, Document_root=settings. Media_root)
OK, try again, the picture sure came out.


So far, ImageField has been able to use the:-)









Django Upload image, ImageField

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.