Django博客教程–创建一个简单的博客

In this tutorial, we’ll discuss about how to make a simple Blog in Django 2.

在本教程中,我们将讨论如何在Django 2中创建简单的Blog。

Our blog will have TITLE, PICTURE, DESCRIPTION (Body), DATE.  There will be two pages, one for showing all the blogs at one place with less information and the second one to show each blog in detail.

我们的博客将包含标题,图片,说明(正文),日期。 将有两个页面,一个页面显示一个信息较少的所有博客,第二个页面显示详细的每个博客。

Prerequisite

先决条件

  • Django 2.0 or above should be installed.

    应该安装Django 2.0或更高版本。
  • Create a project

    建立专案

Django博客教程 (Django Blog Tutorial)

建立应用程式 (Creating App)

I have created a project named as blog_project. Now we’ll create an app for Blog, So in future, if we need to use Blog in other projects then we can use this app.

我创建了一个名为blog_project的项目 现在,我们将为Blog创建一个应用程序。因此,将来,如果需要在其他项目中使用Blog,则可以使用此应用程序。

To create an app, open terminal and navigate to your project folder.

要创建一个应用程序,请打开终端并导航到您的项目文件夹。

Type the command below:

在下面输入命令:

python manage.py startapp blog

python manage.py startapp博客

Now add a path for our newly created app in settings.py. Open settings.py and look for INSTALLED_APPS list.

现在,在settings.py中为我们新创建的应用添加路径。 打开settings.py并查找INSTALLED_APPS列表。

1
2
3
4
5
6
7
8
9
INSTALLED_APPS = [
    'blog.apps.BlogConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
1
2
3
4
5
6
7
8
9
INSTALLED_APPS = [
     'blog.apps.BlogConfig' ,
     'django.contrib.admin' ,
     'django.contrib.auth' ,
     'django.contrib.contenttypes' ,
     'django.contrib.sessions' ,
     'django.contrib.messages' ,
     'django.contrib.staticfiles' ,
]

Add these lines in the last.

在最后添加这些行。

1
2
MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/pics/'
1
2
MEDIA_ROOT = os.path . join ( BASE_DIR , 'media' )
MEDIA_URL = '/pics/'

I have added a path for Blog as first item of the list INSTALLED_APPS. If you’re thinking, from where this BlogConfig have came from instead of Blog, then navigate to your blog app folder and open apps.py file. Here you can see a class name as BlogConfig. This is what we add in settings.py while adding path for app in settings.

我已将Blog的路径添加为列表INSTALLED_APPS的第一项。 如果您在考虑,此BlogConfig的来源而不是Blog的来源,请导航至Blog应用程序文件夹并打开apps.py文件。 在这里,您可以看到一个名为BlogConfig的类名。 这是我们在settings.py中添加的内容,同时在设置中添加应用的路径。

建立模型 (Creating Model)

Open the models.py in your blog app folder and edit it as

在您的博客应用文件夹中打开models.py并将其编辑为

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.db import models
class Blog(models.Model):
    title = models.CharField(max_length=255)
    pub_date = models.DateTimeField()
    image = models.ImageField(upload_to='images/')
    body = models.TextField()
    def summary(self):
        return self.body[:100]
    def pub_date_pretty(self):
        return self.pub_date.strftime('%b %e, %Y')
    def __str__(self):
        return self.title
1
2
3
4
5
6
7
8
9
10
11
12
13
from django . db import models
class Blog ( models . Model ) :
     title = models . CharField ( max_length = 255 )
     pub_date = models . DateTimeField ( )
     image = models . ImageField ( upload_to = 'images/' )
     body = models . TextField ( )
     def summary ( self ) :
         return self . body [ : 100 ]
     def pub_date_pretty ( self ) :
         return self . pub_date . strftime ( '%b %e, %Y' )
     def __str__ ( self ) :
         return self . title

So I’ve created a model to store title, publishing date (pub_date), picture (image) and description (body).  I’ve also created some functions inside the model.

因此,我创建了一个模型来存储标题,发布日期(pub_date),图片(image)和描述(body)。 我还在模型内部创建了一些函数。

  • Summary: summary functions will return us the short info about a blog. For example, on the page where we will show all the blogs, we’ll not display the whole body of each blog. Instead of it we’ll use short info about that blog.

    摘要:摘要功能将向我们返回有关博客的简短信息。 例如,在我们将显示所有博客的页面上,我们不会显示每个博客的整个正文。 取而代之的是,我们将使用有关该博客的简短信息。

  • pub_date_pretty: It will return you the date in this format – Sep 26, 2018, which looks more user friendly then the default date format.

    pub_date_pretty:它将以这种格式返回日期-2018年9月26日,它看起来比默认日期格式更加用户友好。

  • __str__: It is an inbuilt function, I’ve overridden it to return the title instead of object index in the admin panel. You’ll see the result in the admin panel.

    __str__:这是一个内置函数,我已覆盖它以返回标题而不是管理面板中的对象索引。 您将在管理面板中看到结果。

Now in the last, open the admin.py file to register your blog to show on the admin panel and the following lines.

现在,在最后,打开admin.py文件以注册您的博客,以显示在管理面板和以下各行中。

1
2
3
from django.contrib import admin
from .models import Blog
admin.site.register(Blog)
1
2
3
from django . contrib import admin
from . models import Blog
admin . site . register ( Blog )

编辑urls.py (Edit urls.py)

Now edit your main urls.py file and add two url path. First for the homepage where all our blogs will display and second one is for detail page, where each of the blog in detail will be shown up.

现在,编辑您的主urls.py文件,并添加两个url路径。 首先是显示所有博客的首页,其次是显示详细信息页面的详细信息页面,其中将显示每个详细的博客。

1
2
3
4
5
6
7
8
9
10
from django.contrib import admin
from django.urls import path
from blog import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.allblogs , name='allblogs'),
    path('<int:blog_id>/', views.detail, name="detail"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
1
2
3
4
5
6
7
8
9
10
from django . contrib import admin
from django . urls import path
from blog import views
from django . conf . urls . static import static
from django . conf import settings
urlpatterns = [
     path ( 'admin/' , admin . site . urls ) ,
     path ( '' , views . allblogs , name = 'allblogs' ) ,
     path ( '<int:blog_id>/' , views . detail , name = "detail" ) ,
] + static ( settings . MEDIA_URL , document_root = settings . MEDIA_ROOT )

Here we’ve added two paths, one for showing all the blogs and another for showing a particular blog in detail. The empty string in path shows that it is home page and will call views.allblogs function and ‘<int:blog_id>/means it will take integer after domain name and call views.detail function.

在这里,我们添加了两条路径,一条用于显示所有博客,另一条用于详细显示特定博客。 路径中的空字符串表示它是主页,将调用views.allblogs函数,“ <int:blog_id> / 表示它将在域名后取整数并调用views.detail函数。

编辑views.py (Edit views.py)

Open the views.py inside your app blog folder and edit it as:

在您的应用博客文件夹中打开views.py,并将其编辑为:

1
2
3
4
5
6
7
8
9
10
from django.shortcuts import render, get_object_or_404
from .models import Blog
def allblogs(request):
    blogs = Blog.objects
    return render(request, 'blog/allblogs.html', {'blogs':blogs})
def detail(request, blog_id):
    blogdetail = get_object_or_404(Blog, pk=blog_id)
    return render(request, 'blog/detail.html', {'blog':blogdetail})
1
2
3
4
5
6
7
8
9
10
from django . shortcuts import render , get_object_or_404
from . models import Blog
def allblogs ( request ) :
     blogs = Blog . objects
     return render ( request , 'blog/allblogs.html' , { 'blogs' : blogs } )
def detail ( request , blog_id ) :
     blogdetail = get_object_or_404 ( Blog , pk = blog_id )
     return render ( request , 'blog/detail.html' , { 'blog' : blogdetail } )

Firstly we are importing some of modules to work with,

首先,我们要导入一些要使用的模块,

  • render: to return a template on requested.

    render:根据要求返回模板。

  • get_object_or_404: to get the stored objects from database.

    get_object_or_404:从数据库获取存储的对象。

  • Blog: to get the Blog’s objects we have to use this model name.

    Blog:要获取Blog的对象,我们必须使用此模型名称。

After that, we have two functions allblogs() and detail().  allblogs function will get all the stored objects from database of Model Blog and return the template along with all the objects of database.

之后,我们有两个函数allblogs()detail()。 allblogs函数将从Model Blog的数据库中获取所有存储的对象,并返回模板以及数据库中的所有对象。

detail function have an extra parameter inside it – blog_id, this blog_id will be used to get a particular object from the database according to the primary key and the primary key is our blog_id.

detail函数内部有一个额外的参数– blog_id,此blog_id将用于根据主键从数据库中获取特定对象,而主键是我们的blog_id。

After that this function will return user another template along with the particular object.

之后,此函数将返回用户另一个模板以及特定对象。

创建模板 (Create Templates)

  • allblogs.html: create a folder templates inside the blog app, then create another folder inside the template as the same name as app blog, now create allblogs.html here.

    allblogs.html:Blog应用程序中创建一个文件夹模板 然后在模板中创建与app blog同名的另一个文件夹,现在在此处创建allblogs.html

So our project directory will look like this:

因此,我们的项目目录如下所示:

Django博客教程–创建一个简单的博客

And add this code into you allblogs.html:

并将此代码添加到您的allblogs.html中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html>
<body>
       <h1>My Blog</h1>
       <br /> <br />
     <h2>Latest posts</h2>
     <hr/>
     {% for blog in  blogs.all %}
     <a href="{% url 'detail' blog.id %}">  <h3>{{ blog.title }}</h3></a>
      {{ blog.pub_date_pretty }}
      <br />
       <img src = "{{ blog.image.url }}" height=200 width=200/>
       <br />
       <p>{{ blog.summary }}</p>
     {% endfor %}
   &copy; My Blog,  {% now "Y" %}
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html>
<body>
       <h1> My Blog </h1>
       <br /> <br />
     <h2> Latest posts </h2>
     <hr/>
     {% for blog in  blogs.all %}
     <a href = "{% url 'detail' blog.id %}" >    <h3> {{ blog.title }} </h3> </a>
      {{ blog.pub_date_pretty }}
      <br />
        <img src = "{{ blog.image.url }}" height = 200 width = 200 />
        <br />
        <p> {{ blog.summary }} </p>
     {% endfor %}
   &copy; My Blog,  {% now "Y" %}
</body>
</html>

In above code, we’re looping through all the blogs (sent from allblogs function in the views) and printing title of the blog as link, date, image and short summary.

在上面的代码中,我们循环浏览所有博客(从视图中的allblogs函数发送),并将博客标题打印为链接,日期,图像和简短摘要。

When user click on the title, he/she will be navigated to the URL having name detail.

当用户单击标题时,他/她将被导航到具有名称详细信息的URL

  • details.html: create details.html in the same directory as above and edit it as:

    details.html:在与上述相同的目录中创建details.html,并将其编辑为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html>
  <head>
    <title> {{ blog.title }}</title>
  </head>
<body>
      <h1> {{ blog.title }}</h1>
          <p>{{ blog.pub_date }}</p>
      <hr />
      <br />
      <center>
       <img src = "{{ blog.image.url }}"  height=”300” width=”400”/>
      </center>
<br />
      <br/>
      <p>{{ blog.body }}</p>
      &copy; Indrajeet,  {% now "Y" %}
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
< ! doctype html >
< html >
   < head >
     < title > { { blog . title } } < / title >
   < / head >
< body >
       < h1 > { { blog . title } } < / h1 >
           < p > { { blog . pub _ date } } < / p >
       < hr / >
       < br / >
       < center >
       < img src = "{{ blog.image.url }}"    height = ” 300 ” width = ” 400 ” / >
       < / center >
< br / >
       < br / >
       < p > { { blog . body } } < / p >
       & copy ; Indrajeet ,    { % now "Y" % }
   < / body >
< / html >

In above code, we’re just printing the title, publishing date, image , full summary of the particular blog.

在上面的代码中,我们只是打印特定博客的标题,发布日期,图像和完整摘要。

测试中 (Testing)

First migrate unapplied migrations, open your terminal and navigate to the project folder and run:

首先迁移未应用的迁移,打开终端并导航到项目文件夹并运行:

python manage.py migrate

python manage.py迁移

Then run server by typing:

然后输入以下内容运行服务器:

python manage.py runserver

python manage.py运行服务器

Now open browser and open admin panel (http://localhost:8000/admin/) and login to add some data into our databases.

现在打开浏览器并打开管理面板(http:// localhost:8000 / admin /)并登录以将一些数据添加到我们的数据库中。

In case, you don’t have the admin username and password, just stop your server and type this command:

如果您没有管理员用户名和密码,只需停止服务器并键入以下命令:

python manage.py createsuperuser

python manage.py createsuperuser

And create admin account. Then reload the server and open admin panel to add some blog posts.

并创建管理员帐户。 然后重新加载服务器并打开管理面板以添加一些博客文章。

Django博客教程–创建一个简单的博客
Django博客教程–创建一个简单的博客
Django博客教程–创建一个简单的博客

As you can see I have added three blogs. Now let’s open our website’s homepage.

如您所见,我添加了三个博客。 现在,让我们打开我们网站的主页。

Django博客教程–创建一个简单的博客

After clicking on any title:

单击任何标题后:

Django博客教程–创建一个简单的博客

Its working. That’s the simplicity of Django. We can make it more attractive by adding some bootstrap or css.

它的工作。 那就是Django的简单性。 我们可以通过添加一些引导程序或CSS使它更具吸引力。

If you’ve any query related with this article, please let us know in comment box.

如果您对本文有任何疑问,请在评论框中告诉我们。

翻译自: https://www.thecrazyprogrammer.com/2019/02/django-blog-tutorial.html