Python-Django

高洛峰
Release: 2017-02-15 15:30:02
Original
1141 people have browsed it

Preparation work

Create a new Django project

# 新建一个django项目
$ django-admin startproject mysite
# 新建一个app
$ django-admin startapp blog
Copy after login

Project structure

├── blog
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
└── mysite
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py
Copy after login
# mysite/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog', 
    'markdown2'
]
Copy after login
$ python3 manage.py runserver

$ python manage.py collectstatic
Copy after login

Generally configure the url in urls.py, configure the model in models.py, and Configure View in views.py.

urls.py

Function views

1. Add an import:  from my_app import views
2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Copy after login

Class-based views

1. Add an import:  from other_app.views import Home
2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Copy after login

Including another URLconf

1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
Copy after login
# blog/urls.py

from django.conf.urls import url
from blog import views

urlpatterns = [
    url(r'^blog/$', views.IndexView.as_view(), name='index'),
    url(r'^blog/article/(?P<article_id>\d+)$', views.ArticleDetailView.as_view(), name='detail'),
    url(r'^blog/category/(?P<cate_id>\d+)$', views.CategoryView.as_view(), name='category'),
    url(r'^blog/tag/(?P<tag_id>\d+)$', views.TagView.as_view(), name='tag'),
]
Copy after login

Use the form of (?P<>d+) to capture the value for the parameter in <>, such as (?Pd+), when accessing /blog/ When article/3 is used, 3 will be captured to article_id, and this value will be passed to views.ArticleDetailView.

# mysite/urls.py

from django.conf.urls import url, include
from django.contrib import admin
from blog import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('blog.urls', namespace='blog', app_name='blog'))
]
Copy after login

The namespace parameter specifies the namespace for us, which means that the URL in this urls.py is under the blog app, so there will be no conflict even if there are the same URL under different apps.

Assuming that the user wants to access an article, it will automatically parse the URL corresponding to the blog:detail view function, and pass article.pk (the primary key of the article) to the detail view function, details is the name we specified in blog/urls.py.

<a href="{% url &#39;blog:detail&#39; article.pk %}">{{ article.title }}</a>
Copy after login

If you want to access a directory

<a href="{% url &#39;blog:category&#39; category.pk %}">{{ category.name }}</a>
Copy after login

models.py

django.db.models is the basis of the orm framework, in Create three models Article, Category, Tag in blog/models.py.

class Article(models.Model):
    STATUS_CHOICES = (
        ('d', 'Draft'),
        ('p', 'Published'),
    )
    
    # 仍然使用默认的 objects 作为 manager 的名字
    objects = ArticleManager()

    title = models.CharField('标题', max_length=70)
    body = models.TextField('正文')
    created_time = models.DateTimeField('创建时间', auto_now_add=True)
    last_modified_time = models.DateTimeField('修改时间', auto_now=True)
    status = models.CharField('文章状态', max_length=1, choices=STATUS_CHOICES)
    # blank和null要同时设置为null,详情参考官方文档
    abstract = models.CharField('摘要', max_length=54, blank=True, null=True, 
                                help_text="可选,如若为空将摘取正文的前54个字符")
    views = models.PositiveIntegerField('浏览量', default=0)
    likes = models.PositiveIntegerField('点赞数', default=0)
    topped = models.BooleanField('置顶', default=False)
    
    category = models.ForeignKey('Category', verbose_name='分类', null=True, on_delete=models.SET_NULL)
    tags = models.ManyToManyField('Tag', verbose_name='标签集合', blank=True)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-last_modified_time']

    # 新增 get_absolute_url 方法
    def get_absolute_url(self):
        # 这里 reverse 解析 blog:detail 视图函数对应的 url
        return reverse('blog:detail', kwargs={'article_id': self.pk})
Copy after login

Django provides us with many useful fields, such as the above-mentioned CharFiled, TestField, DateTimeFiled, etc. For details, please Refer to official documentation.

One-to-many in Django is set in one, which corresponds to the classification of the article, and ForeignKey is the foreign key in the database. on_delete=models.SET_NULL means that after deleting a category (category), the foreign keys of all Articles under the category are set to null (empty), so we set null=True at the same time. Many-to-many is different, both sides need to be configured. Please refer to the official documentation for details.

class Category(models.Model):
    name = models.CharField('类名', max_length=20)
    created_time = models.DateTimeField('创建时间', auto_now_add=True)
    last_modified_time = models.DateTimeField('修改时间', auto_now=True)

    def __str__(self):
        return self.name
Copy after login
class Tag(models.Model):
    name = models.CharField('标签名', max_length=20)
    created_time = models.DateTimeField('创建时间', auto_now_add=True)
    last_modified_time = models.DateTimeField('修改时间', auto_now=True)

    def __str__(self):
        return self.name
Copy after login

Implementation of comment function

class BlogComment(models.Model):
    user_name = models.CharField('评论者名字', max_length=100)
    user_email = models.EmailField('评论者邮箱', max_length=255)
    body = models.TextField('评论内容')
    created_time = models.DateTimeField('评论发表时间', auto_now_add=True)
    article = models.ForeignKey('Article', verbose_name='评论所属文章', on_delete=models.CASCADE)

    def __str__(self):
        return self.body[:20]
Copy after login
class ArticleManage(models.Manager):
    """
    继承自默认的 Manager ,为其添加一个自定义的 archive 方法
    """
    def archive(self):
        date_list = Article.objects.datetimes('created_time', 'month', order='DESC')
        # 获取到降序排列的精确到月份且已去重的文章发表时间列表
        # 并把列表转为一个字典,字典的键为年份,值为该年份下对应的月份列表
        date_dict = defaultdict(list)
        for d in date_list:
            date_dict[d.year].append(d.month)
        # 模板不支持defaultdict,因此我们把它转换成一个二级列表,由于字典转换后无序,因此重新降序排序
        return sorted(date_dict.items(), reverse=True)
Copy after login

We must first configure the corresponding configuration file in project_name/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}
Copy after login

After the definition is completed, we execute the following command to generate the corresponding data table in the database:

$ python manage.py makemigrations

$ python manage.py migrate
Copy after login

admins.py

Refer to Mozila's tutorials and official documents.

views.py

Markdown2 will be used below, so markdown2 must be added to INSTALLED_APP. However, this mardown parsing is very poor, and after finishing it, you have to download the corresponding markdown css file. , there is a dedicated website.

from blog.models import Article, Tag, Category
from django.views.generic import ListView, DetailView
import markdown2

class IndexView(ListView):
    # template_name属性用于指定使用哪个模板进行渲染
    template_name = "blog/index.html"

    # context_object_name属性用于给上下文变量取名(在模板中使用该名字)
    context_object_name = "article_list"

    def get_queryset(self):
        article_list = Article.objects.filter(status='p')
        for article in article_list:
            article.body = markdown2.markdown(article.body, )
        return article_list

    def get_context_data(self, **kwargs):
        kwargs['category_list'] = Category.objects.all().order_by('name')
        # 调用 archive 方法,把获取的时间列表插入到 context 上下文中以便在模板中渲染
        kwargs['date_archive'] = Article.objects.archive()
        kwargs['tag_list'] = Tag.objects.all().order_by('name')
        return super(IndexView, self).get_context_data(**kwargs)
Copy after login

Because we need to perform markdown processing, we have redefined get_queryset. If we do not want to perform corresponding processing, just formulate model directly, get_context_data can add some additional fields. For example, we will display catalogs and tags in the sidebar of the homepage in the future, so we need to add a category_list and tag_list here.

class ArticleDetailView(DetailView):
    model = Article
    template_name = "blog/detail.html"
    context_object_name = "article"
    # pk_url_kwarg会自动和model中相应的主键对应,aritlce_id就是下面配置的URLCONF
    pk_url_kwarg = 'article_id'

    # 为了让文章以markdown形式展现,我们重写get_object()方法
    def get_object(self):
        obj = super(ArticleDetailView, self).get_object()
        obj.body = markdown2.markdown(obj.body)
        return obj
        
    # 新增 form 到 context
    def get_context_data(self, **kwargs):
        kwargs['comment_list'] = self.object.blogcomment_set.all()
        kwargs['form'] = BlogCommentForm()
        return super(ArticleDetailView, self).get_context_data(**kwargs)
Copy after login
class CategoryView(ListView):
    template_name = "blog/index.html"
    context_object_name = "article_list"
    
    def get_queryset(self):
        # url里的cate_id传递给CategoryView,传递的参数在kwargs属性中获取
        article_list = Article.objects.filter(category=self.kwargs['cate_id'],status='p')
        for article in article_list:
            article.body = markdown2.markdown(article.body, )
        return article_list

    def get_context_data(self, **kwargs):
        # 增加一个category_list,用于在页面显示所有分类,按照名字排序
        kwargs['category_list'] = Category.objects.all().order_by('name')
        return super(CategoryView, self).get_context_data(**kwargs)
Copy after login
class TagView(ListView):
    template_name = "blog/index.html"
    context_object_name = "article_list"

    def get_queryset(self):
        """
        根据指定的标签获取该标签下的全部文章
        """
        article_list = Article.objects.filter(tags=self.kwargs['tag_id'], status='p')
        for article in article_list:
            article.body = markdown2.markdown(article.body, extras=['fenced-code-blocks'], )
        return article_list

    def get_context_data(self, **kwargs):
        kwargs['tag_list'] = Tag.objects.all().order_by('name')
        return super(TagView, self).get_context_data(**kwargs)
Copy after login
from django.views.generic.edit import FormView

class CommentPostView(FormView):
    form_class = BlogCommentForm
    template_name = 'blog/detail.html' 

    def form_valid(self, form):
        target_article = get_object_or_404(Article, pk=self.kwargs['article_id'])
        # 调用ModelForm的save方法保存评论,设置commit=False则先不保存到数据库,
        # 而是返回生成的comment实例,直到真正调用save方法时才保存到数据库。
        comment = form.save(commit=False)
        # 把评论和文章关联
        comment.article = target_article
        comment.save()
        # 评论生成成功,重定向到被评论的文章页面,get_absolute_url 请看下面的讲解。
        self.success_url = target_article.get_absolute_url()
        return HttpResponseRedirect(self.success_url)

    def form_invalid(self, form):
        target_article = get_object_or_404(Article, pk=self.kwargs['article_id'])

        # 不保存评论,回到原来提交评论的文章详情页面
        return render(self.request, 'blog/detail.html', {
            'form': form,
            'article': target_article,
            'comment_list': target_article.blogcomment_set.all(),
        })
Copy after login

template

##{% for %}Loop tag, {% if %}Judge tag. {{ variable }} are some very commonly used tags

We can use it like this in the template file.

context_object_name = "article_list" has been specified in views.py and has been set in get_queryset () Markdown processing is performed in

{% for article in article_list %}
    {{article.title}}
Copy after login
Usually a common parent template is set:

{% extends "base_generic.html" %}

{% block content %}
...
{% endblock %}
Copy after login
It seems to be set like this:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'blog/templates')]
        ,
        'APP_DIRS': True,
...
]
Copy after login
Static file

Due to the loss of the source code, I don’t remember the specific situation clearly. The static file path must be set correctly. If the js file loads abnormally, it may be a problem with the loading order.

base_generic.html is probably in the following format:

<!DOCTYPE html>
{% load staticfiles %}
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Myblog</title>
    <link rel="stylesheet" href="{% static &#39;lib/css/bootstrap.min.css&#39; %}">
    <link rel="stylesheet" href="{% static &#39;blog/css/style.css&#39; %}">
    <link rel="stylesheet" href="{% static &#39;blog/css/pygments/github.css&#39; %}">
</head>
...
Copy after login
There seems to be a problem with the following settings:

# mysite/settings.py
STATIC_URL = '/static/'
STATICFILES = os.path.join(BASE_DIR, 'blog/static')
Copy after login
Please refer to the official documentation for details

Deployment

Use uwsgi+nginx

/etc/nginx/sites-available/mysite.conf, blog is the app name, and the static file is placed below. It is recommended to place it directly under mysite. The same is true for template:

server {
    listen 80;

    location /static/ {
        alias /home/omrsf/mysite/blog/static/;
    }

    location / {
        uwsgi_pass 127.0.0.1:8001;
        include     /etc/nginx/uwsgi_params;
    }
}
Copy after login

uwsgi -i uwsgi.ini to start the uwsgi process, combined with nohup &:

[uwsgi]
socket = 127.0.0.1:8001
chdir=/home/ormsf/mysite/
wsgi-file = mysite/wsgi.py

processes = 2
threads = 4

chmod-socket = 664
Copy after login
improvement

current article The model is registered directly in admin.py, and then published in the admin background. It can be made into an API interface and an online editor. Add basic user authentication function.

Fragmentary knowledge points

The difference between null and blank

  • null is for the database. If null=True, it means that the field of the database can Is empty.

  • blank is for forms. If blank=True, it means that you don’t need to fill in this field when filling in your form, such as when adding a model record in the admin interface. What you can intuitively see is that the field is not bold.

render and render_response

Use render first.

get_absolute_url

model has a get_absolute_url, which can be combined with reverse.

For more Python-Django related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template