Browse Source

完成了文章的分类功能,接下来开发文章的标签功能

Shellmiao 4 years ago
parent
commit
7ee29d5aa1

+ 1 - 0
MyBlog/MyBlog/settings.py

@@ -39,6 +39,7 @@ INSTALLED_APPS = [
     'userprofile',
     'password_reset',
     'comment',
+    'taggit',
 ]
 
 MIDDLEWARE = [

+ 2 - 1
MyBlog/article/admin.py

@@ -1,4 +1,5 @@
 from django.contrib import admin
-from .models import ArticlePost
+from .models import ArticlePost,ArticleColumn
 
 admin.site.register(ArticlePost)
+admin.site.register(ArticleColumn)

+ 28 - 0
MyBlog/article/migrations/0003_auto_20210128_1001.py

@@ -0,0 +1,28 @@
+# Generated by Django 3.1.1 on 2021-01-28 02:01
+
+from django.db import migrations, models
+import django.db.models.deletion
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('article', '0002_articlepost_total_views'),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='ArticleColumn',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('title', models.CharField(blank=True, max_length=100)),
+                ('created', models.DateTimeField(default=django.utils.timezone.now)),
+            ],
+        ),
+        migrations.AddField(
+            model_name='articlepost',
+            name='column',
+            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='article', to='article.articlecolumn'),
+        ),
+    ]

+ 20 - 0
MyBlog/article/migrations/0004_articlecolumn_tags.py

@@ -0,0 +1,20 @@
+# Generated by Django 3.1.1 on 2021-01-28 03:55
+
+from django.db import migrations
+import taggit.managers
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('taggit', '0003_taggeditem_add_unique_index'),
+        ('article', '0003_auto_20210128_1001'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='articlecolumn',
+            name='tags',
+            field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
+        ),
+    ]

+ 15 - 0
MyBlog/article/models.py

@@ -4,6 +4,16 @@ from django.contrib.auth.models import User
 # timezone用于处理时间相关的事物
 from django.utils import timezone
 from django.urls import reverse
+from taggit.managers import TaggableManager
+
+
+class ArticleColumn(models.Model):
+    title = models.CharField(max_length=100, blank=True)
+    created = models.DateTimeField(default=timezone.now)
+    tags = TaggableManager(blank=True)
+
+    def __str__(self):
+        return self.title
 
 
 # 博客文章数据模型
@@ -14,6 +24,11 @@ class ArticlePost(models.Model):
     created = models.DateTimeField(default=timezone.now)  # 使用timezone.now()时 进行数据迁移会,有警告
     updated = models.DateTimeField(default=timezone.now)
     total_views = models.PositiveIntegerField(default=0)
+    column = models.ForeignKey(ArticleColumn,
+                               null=True,
+                               blank=True,
+                               on_delete=models.CASCADE,
+                               related_name='article')
 
     class Meta:
         ordering = ('-created',)

+ 11 - 3
MyBlog/article/views.py

@@ -6,7 +6,7 @@ from django.core.paginator import Paginator
 from django.db.models import Q
 import markdown
 
-from .models import ArticlePost
+from .models import ArticlePost, ArticleColumn
 from .form import ArticlePostForm
 from comment.models import Comment
 
@@ -64,6 +64,8 @@ def article_create(request):
             # 保存数据,但是暂时不提交到数据库中
             new_article = article_post_form.save(commit=False)
             new_article.author = User.objects.get(id=request.user.id)
+            if request.POST['column'] != 'none':
+                new_article.column = ArticleColumn.objects.get(id=request.POST['column'])
             # 将新文章保存到数据库中
             new_article.save()
             return redirect("article:article_list")
@@ -74,7 +76,8 @@ def article_create(request):
     else:
         # 创建表单类实例
         article_post_form = ArticlePostForm()
-        context = {'article_post_form': article_post_form}
+        columns = ArticleColumn.objects.all()
+        context = {'article_post_form': article_post_form, 'columns': columns}
         # 返回模板
         return render(request, 'article/create.html', context)
 
@@ -107,13 +110,18 @@ def article_update(request, id):
             if article_post_form.is_valid():
                 article.title = request.POST['title']
                 article.body = request.POST['body']
+                if request.POST['column'] != 'none':
+                    article.column = ArticleColumn.objects.get(id=request.POST['column'])
+                else:
+                    article.column = None
                 article.save()
                 return redirect("article:article_detail", id=id)
             else:
                 return HttpResponse("表单内容有误,请重新填写")
         else:
             article_post_form = ArticlePostForm()
-            context = {'article': article, 'article_post_form': article_post_form}
+            columns = ArticleColumn.objects.all()
+            context = {'article': article, 'article_post_form': article_post_form, 'columns': columns}
             return render(request, 'article/update.html', context)
     else:
         return HttpResponse("你无权进行此操作")

BIN
MyBlog/db.sqlite3


+ 13 - 0
MyBlog/templates/article/create.html

@@ -18,6 +18,19 @@
                         </label>
                         <input type="text" class="form-control" id="title" name="title">
                     </div>
+                    <!--文章类别-->
+                    <div class="form-group">
+                        <label for="column">分类</label>
+                        <select class="form-control"
+                                id="column"
+                                name="column"
+                        >
+                            <option value="none">请选择分类..</option>
+                            {% for column in columns %}
+                                <option value="{{ column.id }}">{{ column }}</option>
+                            {% endfor %}
+                        </select>
+                    </div>
                     <div class="form-group">
                         <label for="body">
                             文章正文

+ 48 - 22
MyBlog/templates/article/list.html

@@ -44,27 +44,50 @@
         {% endif %}
         <div class="row mt-2">
             {% for article in articles %}
-                <div class="col-4 mb-4">
-                    <div class="card h-100">
-                        <h4 class="card-header">
-                            {{ article.title }}
-                        </h4>
-                        <div class="card-body">
-                            <p class="card-text">
-                                {{ article.body|slice:'100' }}...
-                            </p>
-                        </div>
-                        <div class="card-footer">
-                            <a href="{% url 'article:article_detail' article.id %}" class="btn btn-primary">
-                                阅读本文
+                <div class="col-12">
+                    {% if article.column %}
+                        <button type="button"
+                            class="btn btn-sm mb-2
+                                {% if article.column.title == 'Django' %}
+                                    btn-success
+                                {% elif article.column.title == 'Java' %}
+                                    btn-danger
+                                {% elif article.column.title == 'HTML' %}
+                                    btn-warning
+                                {% endif %}
+                            "
+                        >
+                            {{ article.column }}
+                        </button>
+                    {% endif %}
+                    <!--标题-->
+                    <h4>
+                        <b>
+                            <a href="{% url 'article:article_detail' article.id %}" style="color: black;">
+                                {{ article.title }}
                             </a>
-                            <span>
-                                <small class="col align-self-end" style="color: gray;">
-                                    浏览:{{ article.total_views }}
-                                </small>
-                            </span>
-                        </div>
+                        </b>
+                    </h4>
+                    <!--摘要-->
+                    <div>
+                        <p style="color: gray;">
+                            {{ article.body|slice:'100' }}...
+                        </p>
                     </div>
+                    <!--注脚-->
+                    <p>
+                        <!--附加消息-->
+                        <span style="color: green;">
+                        {{ article.total_views }}浏览&nbsp;&nbsp;&nbsp;
+                    </span>
+                        <span style="color: blue;">
+                        {{ article.created|date:'Y-m-d' }}发布&nbsp;&nbsp;&nbsp;
+                    </span>
+                        <span style="color: darkred;">
+                        {{ article.updated|date:'Y-m-d' }}更新
+                    </span>
+                    </p>
+                    <hr>
                 </div>
             {% endfor %}
 
@@ -78,7 +101,8 @@
                     &laquo;1
                     </a>
                     <span>...</span>
-                    <a href="?page={{ articles.previous_page_number }}&order={{ order }}&search={{ search }}" class="btn btn-secondary">
+                    <a href="?page={{ articles.previous_page_number }}&order={{ order }}&search={{ search }}"
+                       class="btn btn-secondary">
                     {{ articles.previous_page_number }}
                     </a>
                 {% endif %}
@@ -87,11 +111,13 @@
                     {{ articles.number }}
                 </span>
                 {% if articles.has_next %}
-                    <a href="?page={{ articles.next_page_number }}&order={{ order }}&search={{ search }}" class="btn btn-secondary">
+                    <a href="?page={{ articles.next_page_number }}&order={{ order }}&search={{ search }}"
+                       class="btn btn-secondary">
                     {{ articles.next_page_number }}
                     </a>
                     <span>...</span>
-                    <a href="?page={{ articles.paginator.num_pages }}&order={{ order }}&search={{ search }}" class="btn btn-success">
+                    <a href="?page={{ articles.paginator.num_pages }}&order={{ order }}&search={{ search }}"
+                       class="btn btn-success">
                     {{ articles.paginator.num_pages }} &raquo
                     </a>
                 {% endif %}

+ 42 - 24
MyBlog/templates/article/update.html

@@ -1,34 +1,52 @@
 {% extends "base.html" %}
 {% load static %}
 {% block title %}
-更新文章
+    更新文章
 {% endblock title %}
 {% block content %}
-<div class="container">
-    <div class="row">
-        <div class="col-12">
-            <br>
-            <form method="post" action=".">
-                {% csrf_token %}
-                <div class="form-group">
-                    <label for="title">
-                        文章标题
-                    </label>
-                    <input type="text" class="form-control" id="title" name="title" value="{{ article.title }}">
-                </div>
-                <div class="form-group">
-                    <label for="body">
-                        文章正文
-                    </label>
-                    <textarea type="text" class="form-control" id="body" name="body" rows="12">
+    <div class="container">
+        <div class="row">
+            <div class="col-12">
+                <br>
+                <form method="post" action=".">
+                    {% csrf_token %}
+                    <div class="form-group">
+                        <label for="title">
+                            文章标题
+                        </label>
+                        <input type="text" class="form-control" id="title" name="title" value="{{ article.title }}">
+                    </div>
+                    <div class="form-group">
+                        <label for="column">分类</label>
+                        <select class="form-control"
+                                id="column"
+                                name="column"
+                        >
+                            <option value="none">请选择分类..</option>
+                            {% for column in columns %}
+                                <option value="{{ column.id }}"
+                                        {% if column.id == article.column.id %}
+                                        selected
+                                        {% endif %}
+                                >
+                                    {{ column }}
+                                </option>
+                            {% endfor %}
+                        </select>
+                    </div>
+                    <div class="form-group">
+                        <label for="body">
+                            文章正文
+                        </label>
+                        <textarea type="text" class="form-control" id="body" name="body" rows="12">
                         {{ article.body }}
                     </textarea>
-                </div>
-                <button type="submit" class="btn btn-primary">
-                    提交
-                </button>
-            </form>
+                    </div>
+                    <button type="submit" class="btn btn-primary">
+                        提交
+                    </button>
+                </form>
+            </div>
         </div>
     </div>
-</div>
 {% endblock content %}