Actual combat Django: Web Albums Part1

Source: Internet
Author: User

This example, like the previous example, is derived from the Django Web Development Guide and is willing to be rewritten according to the characteristics of the Django 1.7.1.

Django, which is used in the Django Web Development Guide, is version 1.0, which differs greatly from the current version, such as universal views, URLs, processing of static files, and so on. When I first did the example of this book, these changes have brought great distress to the willing, fortunately, the example is much more, slowly mastered some of the rules, and finally changed these instances into a version that can be run under Django 1.7.1.

1. Create Projects and Apps

Let's start by creating the project for this instance, go to the Scripts folder (such as "c:\python32\Scripts") at the DOS command prompt, and then run the following command:

$ django-admin Startproject Gallery

Without any error, the project was created successfully, and then at the DOS command prompt, enter the command to enter the project folder:

CD Gallery

To start creating an app, enter the command at the DOS command prompt:

$ python manage.py startapp items

After the command is executed, the Gallery folder will have an extra folder called items, and the application will be built.

2. Building a model

Edit the items/models.py file as follows:

items/models.py:

 fromDjango.dbImportModels fromDjango.db.modelsImportPermalink fromGallery.fieldsImportThumbnailimagefieldclassItem (models. Model): Name= Models. Charfield (max_length=250) Description=models. TextField ()classmeta:ordering= ['name']            def __str__(self):returnself.name @permalinkdefGet_absolute_url (self):return('Item_detail', None, {'PK': self.id})classPhoto (models. Model): Item=models. ForeignKey (Item) title= Models. Charfield (max_length=100) Image= Thumbnailimagefield (upload_to='Photos') Caption= Models. Charfield (max_length=250, blank=True)classmeta:ordering= ['title']            def __str__(self):returnSelf.title @permalinkdefGet_absolute_url (self):return('Photo_detail', None, {'PK': Self.id})

We've added an image field to the photo class, where Thumbnailimagefield means to invoke a thumbnail handler and we'll talk about it in the next step. upload_to='photos' refers to the folder where the image is uploaded, and if the photos folder does not exist, the program is created automatically.

3. Write a thumbnail handler

In the third row of items/models.py , we used such an import statement:

from Gallery.fields import Thumbnailimagefield

Here Gallery represents the Gallery folder, fields means fields.py This file, Thumbnailimagefield is a class in fields.py, this is the program we use to process image thumbnails, let's write it.

Create a file called fields.py under the Gallery folder and add the following to it:

gellery/fileds.py (Note that this file should not be placed in the project root directory, but should be placed in the same folder as settings.py):

 fromDjango.db.models.fields.filesImportImageField, Imagefieldfile fromPILImportImageImportOSdef_add_thumb (s):"""add '. Thumb ' to the image file name"""Parts= S.split (".") Parts.insert (-1,"Thumb")    ifParts[-1].lower () not inch['JPEG','jpg']: parts[-1] ='jpg'    return ".". Join (Parts)classThumbnailimagefieldfile (imagefieldfile):def_get_thumb_path (self):return_add_thumb (self.path) Thumb_path=Property (_get_thumb_path)def_get_thumb_url (self):return_add_thumb (self.url) Thumb_url=Property (_get_thumb_url)defSave (self, name, content, save=True): Super (Thumbnailimagefieldfile, self). Save (name, content, save) img=Image.open (Self.path) img.thumbnail (Self.field.thumb_width, Self.field.thumb_height), Image.antialias) Img.save (Self.thumb_path)defDelete (self, save=True):ifos.path.exists (Self.thumb_path): Os.remove (Self.thumb_path) Super (Thumbnailimagefieldfile, self). de Lete (Save)classThumbnailimagefield (ImageField):"""generate thumbnails in JPEG format, accept two optional parameters, thumbnail width and height, default setting is 128px;"""Attr_class=Thumbnailimagefieldfiledef __init__(Self, thumb_width=128, thumb_height=128, *args, * *Kwargs): Self.thumb_width=thumb_width self.thumb_height=Thumb_height Super (Thumbnailimagefield, self).__init__(*args, **kwargs)

Note that this file is stored as UTF-8 encoded.

4. Installing PiL

Note In line 2nd of fields.py, we used such an import statement:

from PIL Import Image

This PIL is a common Python class library, and we need to install it before we can use it for thumbnail processing.

In the Python 3.2 environment of the Windows platform, it is recommended to install this version:

https://pypi.python.org/pypi/Pillow/2.6.0

Find the Pillow-2.6.0.win32-py3.2.exe (MD5) and download it and install it directly. Note that this is the version for Python 32-bit.

5. Configuring the media file path

We want to create a folder to store uploaded images, create a folder called Media under the project root folder, and your project folder should be structured like this:

gallery/    manage.py    gallery/    items/    Media/

This path needs to be added to the config file, edit gallery/settings.py, and add the following at the end:

gallery/settings.py:

' /media/ '  'media/')

The first line is the URL of the media file, define the Media_url, the program will automatically insert "/meida/" in the link, this is very important, if it does not, the image of the link will not be displayed correctly.

Media_root is the storage path of the media file, after defining this attribute, the uploaded image will be saved here automatically. If you do not specify Media_root, the program creates the photos folder directly under the project root directory.

6. Activating the Model

First modify the gallery/settings.py This file, find the Installed_apps this setting, change it to look like this:

gallery/settings.py:

Installed_apps = (    'Django.contrib.admin',    'Django.contrib.auth',    'Django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'Django.contrib.staticfiles',    ' Items',)

When editing the settings.py, it is recommended to modify the language and time zone settings, the specific method, please refer to: "Actual Django: official instance Part1"

Then run the following command at the DOS command prompt:

$ python manage.py makemigrations items

To continue running the command at a DOS command prompt:

$ python manage.py Migrate

In this way, the database is built.

7. Create an Administrator account

Run the following command at a DOS command prompt:
$ python manage.py createsuperuser

Then enter the admin, your mailbox, enter the password two times to complete the operation of creating the administrator.

8. Registering apps in the admin interface

Edit the items/admin.py file to make it look like this:

Items/admin.py:

 from Import Admin  from Import Item, Photo class photoinline (admin. Tabularinline):    = Photoclass  itemadmin (admin. Modeladmin):    = [Photoinline]admin.site.register (Item, Itemadmin)    Admin.site.register (Photo) 

We've added a itemadmin here to correlate the items and photos two models, and the Inlines property is used to set the layout of the photos on the admin page.

9. Start the server

Run the following command at a DOS command prompt:

$ python manage.py runserver

After the command executes, you will see a character like this appear:

December, 2014-21:28:44'gallery.settings'starting development Server at http://127.0.0.1:8000/Quit the server with CTRL-break.

This means that the server has successfully started.

We will first visit the management interface, open the browser, in the Address bar to enter:

http://127.0.0.1:8000/admin/

Then enter the admin account and password you just created, log in to the admin interface, and you'll see a screen like this:

"Not to be Continued"

This article copyright to willing to learn all, welcome reprint, reproduced please indicate the author and source. Thank you!
Willing
Starter: Willing to learn Yuan @ Blog Park

Actual combat Django: Web Albums Part1

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.