Actual combat django: small CMS Part1

Source: Internet
Author: User

CMS, the content Management system. The small CMS applications we're going to develop here are similar in structure and blog applications, but we'll be adding some new technologies like workflow, search, editing components, and so on.

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 Cmsproject

Then proceed to the project folder by entering the following command at the DOS command prompt:

CD Cmsproject

Note that most of the later operations are done here, and we call this folder the root folder of the project.

Next, start creating the app and enter the command at the DOS command prompt:

$ python manage.py Startapp cms

After the command executes, a folder called CMS appears under the Project root folder and the app is created.

2. Building a model

Edit the cms/models.py file and change it to the following:

cms/models.py:

 fromMarkdownImportmarkdownImportdatetime fromDjango.dbImportModels fromDjango.db.modelsImportPermalink fromDjango.contrib.auth.modelsImportUserviewable_status= [3, 4]classViewablemanager (models. Manager):defGet_queryset (self): Default_queryset=Super (Viewablemanager, self). Get_queryset ()returnDefault_queryset.filter (status__in=viewable_status)classCategory (models. Model):"""Article categories"""label= Models. Charfield (Blank=true, max_length=50) Slug=models. Slugfield ()classmeta:verbose_name_plural="Categories"    def __str__(self):returnSelf.labelclassStory (models. Model):"""a post in the Content management system"""status_choices= (        (1,"pending Edit"),         (2,"Pending Review"),         (3,"Publish"),        (4,"Archive"),) title= Models. Charfield (max_length=100) Slug=models. Slugfield () Category=models. ForeignKey (Category) markdown_content=models. TextField () html_content= Models. TextField (editable=False) Owner=models. ForeignKey (User) status= Models. Integerfield (Choices=status_choices, default=1) created= Models. Datetimefield (default=datetime.datetime.now) Modified= Models. Datetimefield (default=Datetime.datetime.now)classmeta:ordering= ['Modified'] Verbose_name_plural="Stories"    def __str__(self):returnSelf.title @permalinkdefGet_absolute_url (self):return("cms-story", (), {'Slug': Self.slug}) defSave (self): self.html_content=markdown (self.markdown_content) self.modified=Datetime.datetime.now () Super (story, self). Save () Admin_objects=models. Manager () objects= Viewablemanager ()

Note that the file is to be stored as UTF-8 encoded.

We can see that in the story model, two other models (user and category) are referenced. The first block of code for the model defines a four-stage workflow, and of course you can add more steps to your own process.

As the name implies, the articles to be edited and to be reviewed are what we don't want visitors to see. The difference between publishing and archiving is that the latter is a certain amount of time, changing it to an archive state, restricting it to certain places, such as the home page, but the content is still visible to visitors elsewhere.

After you define status_choices, you define the turn variable.

    • Title: The caption we want to display on the browser's title bar and render page.
    • Slug: The unique name of the page in the URL.
    • Category: article category, which is a foreign key to the category model.
    • The body of the page in Markdown_content:markdown format (markdown is specifically described below).
    • The page text in html_content:html format. We will automatically render it when we edit it. To avoid confusion, you cannot edit the variable directly, so it is not displayed on the edit form that is applied by the Django Admin interface.
    • Owner: The user who owns this content is not necessarily an administrator and may be a different user.
    • Status: The state in the edit workflow;
    • Created: The time that was created is automatically set to the current time (using the Python datetime module).
    • Modified: The modified time is initialized to the current time, and the timestamp is displayed on the content page of the article.

In the meta nested class we also specify a Verbose_name_plural property, which is used to prevent the model from displaying "Storys" in the app.

There is also a Get_absolute_url method for generating permalink, which we have seen in the previous "network album" instance.

Category this model is very simple, with only two variables, one name, and one alias. It is important to note that this is a very convenient way to create a suitable relational model.

Our database contains both published (Status 3 and 4) and unpublished (status 1 and 2) articles. We also need a convenient way to only display the former to the public page of the site, and in the management interface display all.

Although we can use the {% if%} tag in the template to block public pages from displaying unpublished articles, the solution will eventually become cumbersome and repetitive. Because this involves business logic rather than presentation style, this control should be implemented in the model. In the Django development to grasp such a principle, never put the business logic into the template, otherwise the time will be a mess. Templates as long as the display style of things can be, show what the problem of data, or to the model and view to worry about it!

We added this control function to the model through a custom manager, so we added a line below the import statement "viewable_status = [3, 4]" and then the Viewablemanager class, Viewablemanager controls the article data to ensure that only articles with a status equal to 3 or 4 are output.

Next, we use admin_objects = models in the story model. Manager () defines a manager object, because it is defined first, so it is the default manager of our model, so that we can ensure that we edit all state articles in the admin interface.
Then we use objects = Viewablemanager () to create a custom manager instance. We will use this name in the URL configuration and view, so all public pages will receive filtered queryset that are output by the custom Viewablemanager.

As the last part of the model, we rewrote the function save to apply a light box office language called Markdown. The user uses it to enter text in the admin interface, and Markdown provides a simpler way to create Web content.
You can also choose other markup languages. Here we mainly show how to "magically automatically" convert markdown to HTML by rewriting the model's Save method, so that there is no need to perform a conversion operation for each page request.
Of course, there are better options, such as replacing Markdown with a WYSIWYG editor, which you can study on your own.
To use Markdown, you have to download the Markdown module first, that is: https://pypi.python.org/pypi/Markdown/2.5.1, download finished, unzip first, and then use Python setup.py Install command. Do not install the Python module children's shoes, please self-Baidu learn the appropriate method.
How to use good markdown, you can see the information on this page: Http://daringfireball.net/projects/markdown/syntax

3. Activating the model

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

cmsproject/settings.py:

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

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 cms

To continue running the command at a DOS command prompt:

$ python manage.py Migrate

In this way, the database is built.

4. 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.

5. Registering apps in the admin interface

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

cms/admin.py:

 fromDjango.contribImportAdmin fromCms.modelsImportCategory, Storyclassstoryadmin (admin. Modeladmin): List_display= ('title','owner','Status','created','Modified') Search_fields= ('title','content') List_filter= ('Status','owner','created','Modified') Prepopulated_fields= {'Slug': ('title',)}classcategoryadmin (admin. Modeladmin): Prepopulated_fields= {'Slug': ('label',)} Admin.site.register (Category, Categoryadmin) Admin.site.register (story, Storyadmin)

6. Start the server

Run the following command at a DOS command prompt:

$ python manage.py runserver

Remember how to tell if the server was running successfully? There's not much to talk about here.

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: small CMS 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.