Python builds Personal-blog

Source: Internet
Author: User
A few days ago to write the Django Simple blog development Record, put a link bar

Django Easy Blog Development 1 installation, creation, configuration, admin use
Http://www.cnblogs.com/cacique/archive/2012/09/29/2707976.html
Django Easy Blog Development 2 templates and data query
Http://www.cnblogs.com/cacique/archive/2012/09/30/2709143.html
Django Easy Blog Development 3 static files, from applications and customizations
Http://www.cnblogs.com/cacique/archive/2012/10/01/2709668.html
Django Simple Blog Development 4 Comments library usage and AJAX support
Http://www.cnblogs.com/cacique/archive/2012/10/03/2710803.html
Django Simple Blog Development 5 markdown support, code highlighting, Gravatar avatar service

Http://www.cnblogs.com/cacique/archive/2012/10/07/2713703.html

--------------------------------------------------

Django Easy Blog Development 2 templates and data query

First, stick to the project address Https://github.com/goodspeedcheng/sblog because the code is all over it.

Previous blog We introduced the Django installation configuration, new project, new App,app configuration, and the use of admin, let's take a look at the use of templates and the display of model data.

1, first describes how to use the template in the view

Method 1

From django.template Import template, context from
django.http import httpresponse
import datetime

def Current_datetime (Request): Now
    = Datetime.datetime.now ()
    t = Template ("

It uses a templating system, but the template is still embedded in the Python code and does not truly separate data from performance. Now let's put the template in a separate file and have the view load the file to resolve the problem.

Method 2

First create a new templates folder under the project directory and then create a new Sblog folder and base.html file under the templates

Directory structure is

templates/
  -sblog/
  -base.html

Then modify the setting.py

Template_dirs = (
    '/home/gs/blog/templates ',  #替换成自己的templates目录 here with an absolute path, can also be changed to a relative path
    '/home/gs/blog/ Templates/sblog ',
)

Write base.html

<! DOCTYPE html>

This template, called base.html, defines a simple HTML framework document that we will use in all pages of this site. All of the child templates overload, add, or preserve the contents of the base.html block.

{% block%}: All of the {% block%} tags tell the template engine that the child templates can overload these parts. What each {% block%} tab does is tell the template engine that this piece of content under the template will likely be overwritten by the quilt template.

Then create a new blog_list.html in the Sblog directory to add the following

{% extends ' base.html '%}

{% block title%} Blog list {% Endblock%}


{% block content%}
<div class= ' content ' >
    {% for blogs in blog S%}
        

Templates label use See documentation: https://docs.djangoproject.com/en/1.4/topics/templates/

Add content to views.py files under Sblog directory

From django.shortcuts import render_to_response from
sblog.models import Blog


def blog_list (request):
    Blogs = Blog.objects.all () return
    render_to_response ("blog_list.html", {"Blogs": Blogs})

Of course, you can also modify the view before adding a template

Now that the view and the template are complete, let's add the URL.

First modify the blog directory under the urls.py file add

Urlpatterns + = Patterns (('),
    (R ' ^sblog/', include (' Sblog.urls '))

Then modify the Sblog directory to add the urls.py file

#!/usr/bin/python
#-*-coding:utf-8-*-from

django.conf.urls import * urlpatterns


= patterns (' Sblog.views '),
    url (r ' ^bloglist/$ ', ' blog_list ', name= ' bloglist '), 
    # The Name property is given to this URL by the individual name, Can be referenced in templates without worrying about URLs in the URLs file modified by {% URL bloglist%}
)

Now let's open http://127.0.0.1:8080/sblog/bloglist/the blog added under admin is not showing up?

Here are 8080 ports I set myself by default is the case 8000

Of course, you can also add your own display, such as tag author Publish_time

The above steps are not sequential, because they must be completed before they can be displayed in the browser

2, data query and filtering

Because we're just manipulating data can be in terminal operation in terminal open project directory input python manage.py shell "manager.py Shell" command is a way to enable the Python interactive interpreter This method is necessary here, Because Django can know the configuration file of database connection information through it.

In [1]: from sblog.models import Blog

Now you can do the data operation, because the data want more, we are here only query filtering operations

Blog.objects.all ()  # Select all Objects
Blog.objects.filter (caption= ' blogname ')  # using filter () Filter
by blog topic Blog.objects.filter (caption= ' blogname ', id= "1") # can also be multiple conditions
#上面是精确匹配 can also include sex query
Blog.objects.filter (caption__ contains= ' Blogname ')

Blog.objects.get (caption= ' blogname ') # Get a single object throws an exception if the query does not return the result

#数据排序
Blog.objects.order_by ("caption")
Blog.objects.order_by ("-caption")  # Reverse

If you need to sort by more than one field (the second field is used in the same value as the first field), you can use multiple parameters for
Blog.objects.order_by ("caption", "id")

#连锁查询
Blog.objects.filter (caption__contains= ' blogname '). Order_by ("-id")

#限制返回的数据
Blog.objects.filter (caption__contains= ' Blogname ') [0]
Blog.objects.filter (caption__contains= ' blogname ') [0:3]  # can perform a list-like operation

It's a bit long-winded to use order_by every time. Most of the time you usually only sort some of the fields. In this case, Django allows you to specify the default sort method for the model:

Modify models.py

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 '% (Self.caption, Self.author, Self.publish_time)

    class Meta:
        ordering = ['-publish_time ']

3, add the blog display page

Add the blog_show.html file under the Sblog directory and add the following

{% extends ' base.html '%}

{% block title%} {{blog.caption}} {% Endblock%}


{% block content%}
<div class= ' content ' >

views.py Add Blog_show View

From django.http import Http404

def blog_show (request, id= '):
    try:
        blog = Blog.objects.get (id=id)
    Except blog.doesnotexist:
        raise Http404 return
    render_to_response ("blog_show.html", {"blog": Blog})

Modify Sblog under urls.py (if not specified, later modify urls.py file by default is Sblog directory) add the following

URL (r ' ^blog/(?) p<id>\d+)/$ ', ' blog_show ', name= ' Detailblog '),

Modify Blog_list.html

 

To

 
{% URL detailblog blog.id%} blog.id is
URL (r ' ^blog/(?) p<id>\d+)/$ ', ' blog_show ', name= ' Detailblog '),

Of (? p<id>\d+) parameter

Now refresh the following bloglist page blog title is not become a link, click to view it.

Of course now this interface is really ugly mess, okay, I admit that this is not worthy of the interface is called, we still modify it.

The final source code can be seen in the https://github.com/goodspeedcheng/sblog. I hope we can put the wrong place to correct.

Thank you

All of the above can be found in Django Book 2, chapters fourth and fifth and eighth.

Extended reading: https://docs.djangoproject.com/en/1.4/

Recommended Django Best Practices-Chinese version https://github.com/brantyoung/zh-django-best-practices/blob/master/readme.rst/

PS: Senior students to seek internship email: cacique1103#gmail.com

The next article will explain how to write your own form to add a blog

Related Article

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.