Django (a)

Source: Internet
Author: User

Django claims to be "the perfect web framework for developing finite periods." This article refers to the Django Web Development Guide, quickly set up a blog out, in the middle of a lot of knowledge points, here will not be described in detail, if you are first contact with Django, this article will let you have a perceptual understanding of Django, You will be interested in reading the relevant books and documents after completing this article.

Talk less, come on!!.

The environment for this operation:

===================

Windows 7/10

Python 2.7

Django 1.8.2

===================

Create a project

Create MySite Project:

d:/djpy> django-admin.py startproject MySite

Project directory Structure:

manage.py-----A tool inside a Django project that can invoke Django shells and databases.

The settings.py----contains the default settings for the project, including database information, debug flags, and other work variables.

The urls.py-----is responsible for mapping the URL pattern to the application.

Create a blog app

Create a blog app under the MySite directory

D:/pydj> CD MySite
d:/djpy/mysite$ python manage.py Startapp Blog

Directory structure:

Initializing the Admin backend database

Python comes with the SQLite database, Django supports a variety of mainstream databases, here to facilitate the use of SQLite, if you use other databases in the settings.py file set.

Switch to MySite to create the database:

d:/djpy/mysite$ python manage.py syncdb    command is deprecated in Django 1.7. Use the python manage.py migrate instead.

C:\python27\lib\site-packages\django\core\management\commands\syncdb.py:24:removedindjango19warning:the syncdb Command'll be removed in Django 1.9
Warnings.warn ("The SYNCDB command would be removed in Django 1.9", removedindjango19warning)

Operations to perform:
Synchronize unmigrated Apps:staticfiles, messages
Apply all migrations:admin, ContentTypes, Auth, Sessions
Synchronizing Apps without migrations:
Creating tables ...
Running Deferred SQL ...
Installing Custom SQL ...
Running Migrations:
Rendering model states ... Done
Applying contenttypes.0001_initial ... Ok
Applying auth.0001_initial ... Ok
Applying admin.0001_initial ... Ok
Applying Contenttypes.0002_remove_content_type_name ... Ok
Applying auth.0002_alter_permission_name_max_length ... Ok
Applying auth.0003_alter_user_email_max_length ... Ok
Applying auth.0004_alter_user_username_opts ... Ok
Applying Auth.0005_alter_user_last_login_null ... Ok
Applying auth.0006_require_contenttypes_0002 ... Ok
Applying sessions.0001_initial ... Ok

You have installed Django ' s auth system, and don ' t has any superusers defined.
Would to create one now? (yes/no): Yes
Username (leave blank to use ' fnngj '): Username (default current system user name)
Email address: [email protected] e-mail
Password: Password
Password (again): duplicate password
Superuser created successfully.

Setting the Admin app

  

Admin is a backend management system that Django comes with.

1, add Blog application, open mysite/mysite/settings.py file:

# application Definitioninstalled_apps = (    ' django.contrib.admin ',    ' Django.contrib.auth ',    ' Django.contrib.contenttypes ',    ' django.contrib.sessions ',    ' django.contrib.messages ',    ' Django.contrib.staticfiles ',    ' blog ',)

At the end of the list, add a blog app

2. When we create a Django project, admin has created and opened the mysite/mysite/urls.py file:

From Django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [    url (R ' ^admin/', include ( Admin.site.urls)),]

3. Start the Django container

D:\pydj\mysite>python manage.py runserverperforming System checks ... System Check identified no issues (0 silenced). October, 2015-20:56:45django version 1.8.2, using Settings ' mysite.settings ' starting development Server at http://127 .0.0.1:8000/quit the server with Ctrl-break.

4. Access to Background applications

Http://127.0.0.1:8000/admin

Enter the user, password, and password for the user name that was created the first time the database was created. Recall the settings when setting up the database.

design model (i.e. Design database table)

1. Design Model

Now we open the blog directory under the models.py file, which is where we define the data structure of the blog. Open the mysite/blog/models.py file for modification:

From django.db import modelsfrom django.contrib import admin# Create your models Here.class blogspost (models. Model):    title = models. Charfield (max_length =)    BODY = models. TextField ()    timestamp = models. Datetimefield () Admin.site.register (blogspost)

2. Initialize the database again

D:\pydj\mysite>python manage.py makemigrations blogmigrations for ' blog ':  0001_initial.py:    -Create model Blogspostd:\pydj\mysite>python manage.py syncdbc:\python27\lib\site-packages\django\core\management\commands\ Syncdb.py:24:removedindjango19warning:the syncdb command would be removed in Django 1.9  Warnings.warn ("The SYNCDB com Mand'll be removed in Django 1.9 ", removedindjango19warning) Operations to perform:  Synchronize unmigrated Apps:stat Icfiles, Messages  Apply all migrations:admin, blog, contenttypes, auth, sessionssynchronizing apps without migration S:  Creating tables    ... Running Deferred SQL ...  Installing Custom SQL ... Running migrations:  Rendering model states ... Done  applying blog.0001_initial ... Ok

3, again runserver start the service, Access Admin backstage, create the article.

Login successful Select Add to create a blog

Enter the blog title, body, Date time, click Save to create a blog.

Setting the admin's Blogspost interface

Open the mysite/blog/models.py file and make the following changes:

From django.db import modelsfrom django.contrib import admin# Create your models Here.class blogspost (models. Model):    title = models. Charfield (max_length =)    BODY = models. TextField ()    timestamp = models. Datetimefield () class blogpostadmin (admin. Modeladmin):    list_display = (' title ', ' timestamp ')    admin.site.register (blogspost,blogpostadmin)

Create the Blogpostadmin class and inherit the admin. Modeladmin the parent class that displays the title and time of the blogpost as a list.

Create a public part of a blog

From a Django perspective, a page has three typical components:

A template: The template is responsible for displaying the information that is passed in.

A view: The view is responsible for getting the information that needs to be displayed from the database.

A URL pattern: it is responsible for matching the received request with your attempted function, and sometimes passing some parameters to the view.

Create a template

Create the Templates directory under the blog Project (mysite/blog/templates/) and create the template file index.html under the directory as follows:

{% for post in posts%}    

Create a View function

Open mysite/blog/views.py File:

#coding =utf-8from django.shortcuts Import renderfrom blog.models import blogspostfrom django.shortcuts import render_to _response# Create Your Views Here.def index (Request):    blog_list = BlogsPost.objects.all ()    return render_to_ Response (' index.html ', {' blog_list ': blog_list})

Blog_list = BlogPost.objects.all (): Gets the Blogpost object owned by the database

Render_to_response () returns a page (index.html) and returns all the blog contents (blog_list) that are queried in the database.

Create a URL pattern for a blog

Add the URL of the blog in the mysite/urls.py file:

#coding =utf-8from django.conf.urls Import patterns, include, urlfrom django.contrib import adminurlpatterns = Patterns (' ',    url (r ' ^admin/', include (Admin.site.urls)),    URL (r ' ^index/$ ', ' Blog.views.index '),)

Start the service again ($ python manage.py runserver), Access the blog app (http://127.0.0.1:8000/index/) in error, for informational purposes only.

The page is as follows:

Of course, the reader can continue to the admin background to add the blog, so refresh the page to show whether the newly added blog.

Add Style

Create a base template

Create a template for base.html in the Mysite/blog/templates directory:

Modify the index.html template so that it references the base.html template and its "content" block.

{% extends "base.html"%}  {% block content%}      {% for post in posts%}      

Refresh the blog page again:

Http://127.0.0.1/index/is wrong and is for reference only.

Please systematically learn the Django Web framework and then do more extensions on this basis to develop your own real blog.

Django (a)

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.