Django Learn notes--first day--Build a simple blog

Source: Internet
Author: User
Tags auth sessions sqlite sqlite database administrator password

Foreword: Recently prepares to write a own personal blog. Originally intended to be developed with. NET, since vs is a bit of a load, recently learning Python. Select the Python web frame Django.
development environment: Ubuntu 14.04
Development tools: Pychram 2016.1.0 Community Edition
python version: 2.7.6
Django version: 1.9.6
< reference >-Previous articles: http://my.oschina.net/jastme/blog/345265
Here's the start:
1. Tool Installation:
Python has taken its own; open Pychram
File–>settings–>project **–>project Interpreter
Click on the green + number, search django–> Select Install Package can be installed to complete.

Input: Import Django
Verify that the installation is successful. If there is no error, indicate success.

2. Create the project
PS: The path is best not to include Chinese, or it will error
Open Terminal input:

django-admin.py startproject mysite
cd mysite
python manage.py startapp Blog
django-admin.py Startproject MySite

Many new engineering files have been created:

The tools within the Manage.py-–django project allow you to invoke the Django shell and database.

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

Urls.py-– is responsible for mapping the URL pattern to the application.

Python manage.py Startapp Blog

Create a blog application
Open the project with Pychram: You can see the following file structure:

And then inside the/mysite/mysite/settings.py.

Installed_apps = [
    ' django.contrib.admin ',
    ' Django.contrib.auth ', '
    django.contrib.contenttypes ',
    ' django.contrib.sessions ',
    ' django.contrib.messages ', '
    django.contrib.staticfiles ',
]

Add ' blog ',

Installed_apps = [
    ' django.contrib.admin ',
    ' Django.contrib.auth ', '
    django.contrib.contenttypes ',
    ' django.contrib.sessions ',
    ' django.contrib.messages ', '
    django.contrib.staticfiles
    ', ' Blog ',
]

Represents adding a blog app

3. Database Creation
Django uses code to create a database.
First modify mysite/blog/models.py inherit the default database class, create the database

From __future__ import unicode_literals to
django.db import Models
# Create your models here.
Class blogpost (models. Model):
    title = models. Charfield (max_length =) body
    = models. TextField ()
    timestamp = models. Datetimefield ()

The blogpost class is a subclass of the Django.db.models.Model. It has variable title (blog title), Body (blog content part), timestamp (blog Published time)

Here only the database is designed and the database is not created.
Dajango supports mainstream database servers (Mysql,postgresql,oracle and MSSQL), but this project uses SQLite, where a simple command is needed to create a SQLite database. Need to be modified in the settings, default to Sqlite3

DATABASES = {'
    default ': {
        ' ENGINE ': ' Django.db.backends.sqlite3 ', '
        NAME ': Os.path.join (Base_dir, ' Db.sqlite3 '),
    }

To create a database:
Switch to a directory containing manage.py:

Python manage.py makemigrations 
python manage.py migrate

4. Background Management
The Django default opens the admin background:

Urlpatterns = [
    url (R ' ^admin/', admin.site.urls),
]

Terminal input: Python manage.py runserver Open Service (price one parameter can set the port number)
Access Http://127.0.0.1:8000/admin Access background

Administrator Password account required:
Terminal input:

Python manage.py Createsuperuser

Create according to the prompts.
Five. Modify the contents of the database to add additional items.
Add a line of code at the end:

Admin.site.register (blogpost)

Add earlier:

From Django.contrib Import admin

There's one more blogpost.

add–> Add an article, you can start writing articles.

Then the background interface to do an optimization, so that the title of the article Time to show
Modify the models.py of the blog application and add a admin.modeladmin subclass blogpostadmin to it. Displays the title and time of the blogpost in a list.
Complete code :

From django.db import models to
django.contrib import Admin

# Create your models here.
Class blogpost (models. Model):
    title = models. Charfield (max_length =) body
    = models. TextField ()
    timestamp = models. Datetimefield ()

class blogpostadmin (admin. Modeladmin):
    list_display = (' title ', ' timestamp ')

admin.site.register (blogpost,blogpostadmin)

six. The Backstage blog elegant display to the front desk to go
Blog Below a new templates folder, where you can place a variety of resources, will be found here by default.
Create a new template page under the templates.
Muban.html

<! DOCTYPE html>

where {{}} contains the variables to display, and a for loop is used to display all the articles on the page.

The view blog/views contains the page style to display.
Call the template here and pass in the parameters:

From django.shortcuts import render to
django.template import loader,context from
django.http Import HttpResponse from
blog.models import blogpost

# Create your views here.

def muban (Request):
    posts = BlogPost.objects.all ()
    t = loader.get_template ("muban.html")
    c = Context ({ ' Posts ':p OSTs}) return
    HttpResponse (T.render (c))
Posts = BlogPost.objects.all (): Get the Blogpost object in the database T = loader.get_template ("archive.html"): Load Template c = context ({' posts '): Posts}): The rendering data for the template is provided by the object context of a dictionary class, where a pair of key values are pairs.

It is still not possible to display the blog page because the request was first processed in Mysite/urls,
So to add a URL to the blog views inside.

From django.conf.urls import URL from
django.contrib import admin from
Blog import views as blog_views  # new
  urlpatterns = [
    url (R ' ^blog ', Blog_views.muban, name= ' muban '),  # new
    URL (r ' ^admin/', admin.site.urls) ,
]

Open service, Access http://127.0.0.1:8000/blog/

Seven. Beautify the interface
Create a template called base.html in the Mysite/blog/templates directory

<! DOCTYPE html>

Inherit Template:
Muban.html

<! DOCTYPE html>

Sort by date

Modify the models.py under the blog application to add a meta nested class for blogpost. As follows:

Class blogpost (models. Model): 
  title = models. Charfield (max_length =) body    
  = models. TextField ()    
  timestamp = models. Datetimefield ()    
  class Meta:        
    ordering = ('-timestamp ',)

Refresh Browser:

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.