Django development blog (1) entry, django blog

Source: Internet
Author: User
Tags django website

Django development blog (1) entry, django blog

Now officially start blog Development

1. Install django1.4

If you are using fedoraDVD, you can skip this step by selecting web development components during installation because it comes with the django environment.

Django https://www.djangoproject.com/download/ here we choose the latest version

Then open the download directory under the terminal

tar xzvf Django-*.tar.gz 。cd Django-* 。sudo python setup.py install

If Windows

Decompress the package and go to the decompressed directory on the console.

python setup.py install

 

Test installation

Open the Python Interpreter

If the following content appears, the installation is successful!

>>> import django>>> django.VERSION(1, 4, 1, 'final', 0)

2. Create a project

Open terminal Input

django-admin startproject blog

Enter

django-admin.py startproject blog

You will find that there is an extra blog directory in the main folder.

The directory structure is

blog/    manage.py    blog/        __init__.py        settings.py        urls.py        wsgi.py

Manage. py: A command line tool that allows you to interact with this Django project in multiple ways. TypePython manage. py helpTo see what it can do.

_ Init _. py: Let Python treat this directory as a file required by an Development Kit (that is, a group of modules. This is an empty file. You do not need to modify it.

Settings. py: Set or configure the Django project. View and understand the available setting types and their default values in this file.

Urls. py: Configure the django project URL. It can be viewed as the directory of your django website

Wsgi. py: An entry-point for WSGI-compatible webservers to serve your project. SeeHow to deploy with WSGIFor more details.

Detailed usage reference document https://docs.djangoproject.com/en/1.4/intro/tutorial01/

Running Server

Open the project directory input on the terminal

python manage.py runserver
Validating models...0 errors foundDjango version 1.4.1, using settings 'blog.settings'Development server is running at http://127.0.0.1:8000/Quit the server with CONTROL-C.

The preceding options indicate that the server is running successfully.

Access http: // 127.0.0.1: 8000/you will see

3. Create a blogapp

Open the project directory input on the terminal

python manage.py startapp sblog

Now a new blog application named sblog has been created.

sblog/    __init__.py    models.py    tests.py    views.py

This directory contains the model and view of this app.

4. models Configuration

Because the app must use the database, now let's configure the database to open setting. py

DATABASES = {'default': {'Engine ': 'django. db. backends. sqlite3 ', # Add 'postgresql _ psycopg2', 'mysql', 'sqlite3 'or 'oracle '. 'name': '/home/gs/blog/datas/mydata. db', # Here is the directory where my database files are stored. You should replace it with your own. 'user': '', # Not used with sqlite3. 'Password':'', # Not used with sqlite3. 'host': '', # Set to empty string for localhost. not used with sqlite3. 'Port': '', # Set to empty string for default. not used with sqlite3 .}}

 

Because python comes with sqlite3, we can use it directly for convenience.

For other database configurations, see https://docs.djangoproject.com/en/1.4/ref/databases/

Now we configure models. py

from django.db import modelsclass Tag(models.Model):    """docstring for Tags"""    tag_name = models.CharField(max_length=20, blank=True)    create_time = models.DateTimeField(auto_now_add=True)    def __unicode__(self):        return self.tag_nameclass Author(models.Model):    """docstring for Author"""    name = models.CharField(max_length=30)    email = models.EmailField(blank=True)    website = models.URLField(blank=True)    def __unicode__(self):        return u'%s' % (self.name)class Blog(models.Model):    """docstring for Blogs"""    caption = models.CharField(max_length=50)    author = models.ForeignKey(Author)    tags = models.ManyToManyField(Tag, blank=True)    content = models.TextField()    publish_time = models.DateTimeField(auto_now_add=True)    update_time = models.DateTimeField(auto_now=True)    def __unicode__(self):        return u'%s %s %s' % (self.caption, self.author, self.publish_time)

 

Install models

First modify setting. py

MIDDLEWARE_CLASSES = (    'django.middleware.common.CommonMiddleware',    'django.contrib.sessions.middleware.SessionMiddleware',    'django.middleware.csrf.CsrfViewMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',    'django.contrib.messages.middleware.MessageMiddleware',    'django.middleware.locale.LocaleMiddleware',    # Uncomment the next line for simple clickjacking protection:    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',)INSTALLED_APPS = (    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.sites',    'django.contrib.messages',    'django.contrib.staticfiles',    # Uncomment the next line to enable the admin:'django.contrib.admin',    # Uncomment the next line to enable admin documentation:    'django.contrib.admindocs',      'sblog',   )

 

Then, run the following command to verify the validity of the model:

python manage.py validate

ValidateCommand to check whether the syntax and logic of your model are correct. If everything is normal, you will see0 errors foundMessage. If there is a problem, it will provide a very useful error message to help you correct your model.

Last

python manage.py syncdb

You will see something similar to the following:

Creating tables ...Creating table auth_permissionCreating table auth_group_permissionsCreating table auth_groupCreating table auth_user_user_permissionsCreating table auth_user_groupsCreating table auth_userCreating table django_content_typeCreating table django_sessionCreating table django_siteCreating table django_admin_logCreating table sblog_tagCreating table sblog_authorCreating table sblog_blog_tagsCreating table sblog_blog

 

Because when we modify setting. py

'django.contrib.admin','django.contrib.admindocs',

The comment is removed. Therefore

python manage.py syncdb
When You just installed Django's auth system appears, which means you don't have any superusers defined. wocould you like to create one now? (Yes/no): Let's create a user for admin management and create a user.5. Use admin ConfigurationModify urls. py in the blog directory to add
from django.contrib import adminadmin.autodiscover()
Add in patterns (if the file has not been changed, you only need to remove the comments from the two lines)
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),url(r'^admin/', include(admin.site.urls)),

Enable http: // 127.0.0.1: 8000/admin/

You can use admin. After logon, the interface is:

If you find that the newly created sblog does not appear, congratulations! You are very good at observation, very careful, very ....

Let me talk about how to use admin to manage our sblog.

First, create admin. py in the sblog directory and add the following content. Then, refresh the admin page.

#! /Usr/bin/python #-*-coding: UTF-8-*-from django. contrib import adminfrom sblog. models import Author, Blog, Tagclass AuthorAdmin (admin. modelAdmin): "docstring for AuthorAdmin" list_display = ('name', 'email ', 'website') search_fields = ('name',) class BlogAdmin (admin. modelAdmin): "docstring for BlogAdmin" "list_display = ('caption ', 'id', 'author', 'Publish _ Time') list_filter = ('Publish _ tim E ',) date_hierarchy = 'Publish _ time' ordering = ('-publish_time ',) filter_horizontal = ('tags',) # raw_id_fields = ('author ',) # It is a tuple containing the name of a foreign key field, and its fields are displayed as ''text'', instead of ''drop-down box ''. Admin. site. register (Author, AuthorAdmin) admin. site. register (Blog, BlogAdmin) admin. site. register (Tag)

AuthorAdmin and BlogAdmin are custom ModelAdmi classes for custom admin display.

List_display = ('caption ', 'id', 'author', 'Publish _ Time') indicates to display the data according to the caption id author publish_time, click the column header of each column to sort the column.

Search_fields = ('name',) refresh the browser and you will see a query bar at the top of the page. On the modification list page, we added a query box by name.

List_filter = ('Publish _ time',) is used to generate a filter on the right side and filter by posting time.

Date_hierarchy = 'Publish _ time' is also the time Filter Modified, the top of the list on the page will have a layer-by-layer navigation bar, which starts from the available year, and then subdivided into months and even days.

Ordering = ('-publish_time',) sort by posting time. By default, add '-' to sort the last published data to the front, and sort the data in descending order from the back to the front.

Filter_horizontal = ('tags',) is used to display multiple-to-multiple fields. A sophisticated JavaScript filter is displayed, which allows you to search for options and then move the selected tag from the Available box to the Chosen box, it can be moved back.

For other custom methods, see the document https://docs.djangoproject.com/en/1.4/ref/contrib/admin/.

So far, we can use admin to manage our blog

[Django blog Development] series of articles:
  • Common django commands
  • Django development blog (1) getting started
  • Django development blog (2) template and Data Query
  • Django development blog (3) static files, from applications and custom
  • Django development blog (4) use of comments library and ajax support
  • Django development blog (5) markdown support, code highlighting, gravatar Avatar Service
  • Django Best Practices (Chinese Version)

 

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.