Table of Contents
Preparation work
urls.py
models.py
admins.py
views.py
template

Python-Django

Feb 15, 2017 pm 03:30 PM
django python

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

See all articles