Django快速入门12:报纸实例

2021-07-28  本文已影响0人  python测试开发

现在是时候建立我们的报纸应用了。我们将有一个文章页面,记者可以在那里发布文章,设置权限,最后还可以让其他用户在每篇文章上写评论。

创建文章应用

$ python manage.py startapp articles
$ vi config/settings.py
# config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 3rd Party
    'crispy_forms',

    # Local
    'accounts',
    'pages',
    'articles', # new
]

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'

接下来我们定义我们的数据库模型,它包含四个字段:标题、正文、日期和作者。注意,我们让Django根据我们的TIME_ZONE设置来自动设置时间和日期。对于作者字段,我们要引用我们的自定义用户模型 "accounts.CustomUser",我们在config/settings.py文件中设置了AUTH_USER_MODEL。

articles/models.py

# articles/models.py
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse


class Article(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey()
        get_user_model(),
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('article_detail', args=[str(self.id)] )

数据迁移

$ python manage.py makemigrations articles
$ python manage.py migrate

articles/admin.py

# articles/admin.py
from django.contrib import admin
from .models import Article

admin.site.register(Article)

现在我们启动服务器。

 $ python manage.py runserver

导航到 http://127.0.0.1:8000/admin/ 并登录。

URLs和视图

config/urls.py

# config/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('articles/', include('articles.urls')), # new
    path('', include('pages.urls')),
]

articles/urls.py

# articles/urls.py
from django.urls import path
from .views import ArticleListView

urlpatterns = [
    path('', ArticleListView.as_view(), name='article_list'),
]

articles/views.py

from django.views.generic import ListView
from .models import Article


class ArticleListView(ListView):
    model = Article
    template_name = 'article_list.html'

templates/article_list.html

<!-- templates/article_list.html -->
{% extends 'base.html' %}

{% block title %}Articles{% endblock title %}

{% block content %}
  {% for article in object_list %}
    <div class="card">
      <div class="card-header">
        <span class="font-weight-bold">{{ article.title }}</span> &middot;
        <span class="text-muted">by {{ article.author }} |
        {{ article.date }}</span>
      </div>
      <div class="card-body">
        {{ article.body }}
      </div>
      <div class="card-footer text-center text-muted">
        <a href="#">Edit</a> | <a href="#">Delete</a>
      </div>
    </div>
    <br />
  {% endfor %}
{% endblock content %}

http://127.0.0.1:8000/articles/,查看我们的页面。

编辑/删除

articles/urls.py

articles/urls.py
# articles/urls.py
from django.urls import path
from .views import (
    ArticleListView,
    ArticleUpdateView, # new
    ArticleDetailView, # new
    ArticleDeleteView, # new
)

urlpatterns = [
    path('<int:pk>/edit/',
         ArticleUpdateView.as_view(), name='article_edit'), # new
    path('<int:pk>/',
         ArticleDetailView.as_view(), name='article_detail'), # new
    path('<int:pk>/delete/',
         ArticleDeleteView.as_view(), name='article_delete'), # new
    path('', ArticleListView.as_view(), name='article_list'),
]

articles/views.py

# articles/views.py
from django.views.generic import ListView, DetailView # new
from django.views.generic.edit import UpdateView, DeleteView # new
from django.urls import reverse_lazy # new
from .models import Article


class ArticleListView(ListView):
    model = Article
    template_name = 'article_list.html'


class ArticleDetailView(DetailView): # new
    model = Article
    template_name = 'article_detail.html'


class ArticleUpdateView(UpdateView): # new
    model = Article
    fields = ('title', 'body',)
    template_name = 'article_edit.html'


class ArticleDeleteView(DeleteView): # new
    model = Article
    template_name = 'article_delete.html'
    success_url = reverse_lazy('article_list')

templates/article_detail.html

<!-- templates/article_detail.html -->
{% extends 'base.html' %}

{% block content %}
  <div class="article-entry">
    <h2>{{ object.title }}</h2>
    <p>by {{ object.author }} | {{ object.date }}</p>
    <p>{{ object.body }}</p>
  </div>

  <p><a href="{% url 'article_edit' article.pk %}">Edit</a> |
    <a href="{% url 'article_delete' article.pk %}">Delete</a></p>
  <p>Back to <a href="{% url 'article_list' %}">All Articles</a>.</p>
{% endblock content %}

templates/article_edit.html

<!-- templates/article_edit.html -->
{% extends 'base.html' %}

{% block content %}
  <h1>Edit</h1>
  <form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <button class="btn btn-info ml-2" type="submit">Update</button>
  </form>
{% endblock content %}

templates/article_delete.html

<!-- templates/article_delete.html -->
{% extends 'base.html' %}

{% block content %}
  <h1>Delete</h1>
  <form action="" method="post">{% csrf_token %}
    <p>Are you sure you want to delete "{{ article.title }}"?</p>
    <button class="btn btn-danger ml-2" type="submit">Confirm</button>
  </form>
{% endblock content %}

templates/article_list.html

<!-- templates/article_list.html -->
...
<div class="card-footer text-center text-muted">
  <a href="{% url 'article_edit' article.pk %}">Edit</a> |
  <a href="{% url 'article_delete' article.pk %}">Delete</a>
</div>
...

好了,我们准备好查看我们的工作了。用python manage.py runserver启动服务器,并在http://127.0.0.1:8000/articles/,导航到文章页面。点击第一篇文章上的 "编辑 "链接,你将被重定向到http://127.0.0.1:8000/articles/1/edit/

创建页面

articles/views.py

# articles/views.py
...
from django.views.generic.edit import (
  UpdateView, DeleteView, CreateView # new
)
...
class ArticleCreateView(CreateView): # new
    model = Article
    template_name = 'article_new.html'
    fields = ('title', 'body', 'author',)

注意,我们的字段有author,因为我们想把新文章和作者联系起来,但是一旦文章被创建,我们不希望用户能够改变作者,这就是为什么ArticleUpdateView只有字段['title', 'body',]。

用视图的新路线更新我们的URLS文件。

articles/urls.py

# articles/urls.py
from django.urls import path

from .views import (
    ArticleListView,
    ArticleUpdateView,
    ArticleDetailView,
    ArticleDeleteView,
    ArticleCreateView, # new
)

urlpatterns = [
    path('<int:pk>/edit/',
         ArticleUpdateView.as_view(), name='article_edit'),
    path('<int:pk>/',
         ArticleDetailView.as_view(), name='article_detail'),
    path('<int:pk>/delete/',
         ArticleDeleteView.as_view(), name='article_delete'),
    path('new/', ArticleCreateView.as_view(), name='article_new'), # new
    path('', ArticleListView.as_view(), name='article_list'),
]

templates/article_new.html

<!-- templates/article_new.html -->
{% extends 'base.html' %}

{% block content %}
  <h1>New article</h1>
  <form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <button class="btn btn-success ml-2" type="submit">Save</button>
  </form>
{% endblock content %}

最后,我们应该在导航条上添加一个创建新文章的链接,这样,登录的用户就可以在网站的任何地方访问它。

templates/base.html 增加if部分内容

<!-- templates/base.html -->
<body>
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a>
    {% if user.is_authenticated %}
      <ul class="navbar-nav mr-auto">
        <li class="nav-item">
          <a href="{% url 'article_new' %}">+ New</a>
        </li>
      </ul>
    {% endif %}

templates/home.html

<!-- templates/home.html -->
{% extends 'base.html' %}

{% block title %}Home{% endblock title %}

{% block content %}
  <br/>
  <div class="jumbotron">
    <h1 class="display-4">Newspaper app</h1>
    <p class="lead">A Newspaper website built with Django.</p>
    <p class="lead">
      <a class="btn btn-primary btn-lg" href="{% url 'article_list' %}"
      role="button">View All Articles</a>
    </p>
  </div>
{% endblock content %}

小结

我们已经创建了一个具有CRUD功能的专用文章应用程序。但是还没有任何权限或授权,这意味着任何人都可以做任何事情! 一个已登录的用户可以访问所有的URL,任何已登录的用户都可以对现有的文章进行编辑或删除,即使是不属于他们自己的文章。下一章,我们将为我们的项目添加权限和授权来解决这个问题。

上一篇 下一篇

猜你喜欢

热点阅读