使用Python的Django框架制作简单的文章发布系统(mysql+bootstrap)

Python 290℃

1.安装`django、mysqlclient`库:

pip install django mysqlclient -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

2.创建项目和应用:

django-admin startproject mysite
cd mysite
python manage.py startapp blog

3.在`mysite/settings.py`中配置MySQL数据库和注册应用:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

INSTALLED_APPS = [
    ......
    'blog',
]

4.在`blog/models.py`文件中创建模型:

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

5.创建数据表(根据模型迁移数据):

python manage.py makemigrations
python manage.py migrate

6.创建`blog/forms.py`文件,并在其中创建表单,用来处理文章发布:

from django import forms
from .models import Article

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ['title', 'content']
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'content': forms.Textarea(attrs={'class': 'form-control'}),
        }

7.在`blog/views.py`文件中创建视图,用来处理文章的发布和浏览:

from django.shortcuts import render, redirect, get_object_or_404
from .models import Article
from .forms import ArticleForm

def article_list(request):
    articles = Article.objects.all()
    return render(request, 'blog/article_list.html', {'articles': articles})

def article_create(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('article_list')
    else:
        form = ArticleForm()
    return render(request, 'blog/article_create.html', {'form': form})

def article_detail(request, article_id):
    article = get_object_or_404(Article, id=article_id)
    return render(request, 'blog/article_detail.html', {'article': article})

8.创建`blog/templates/blog`目录,并在下面创建三个模板文件:
文章列表`article_list.html`:

{% extends 'base.html' %}

{% block content %}
  <h2>文章列表</h2>
  <ul>
    {% for article in articles %}
      <li>
        <a href="{% url 'article_detail' article.id %}">{{ article.title }}</a>
        <small> {{ article.pub_date }}</small>
      </li>
    {% endfor %}
  </ul>
  <a href="{% url 'article_create' %}">发布新文章</a>
{% endblock %}

发布文章`article_create.html`:

{% extends 'base.html' %}

{% block content %}
        <h2>发布新文章</h2>
        <form method="post">
            {% csrf_token %}
            <div>
                <label for="id_title">标题:</label>
                <div>{{ form.title }}</div>
            </div>
            <div>
                <label for="id_content">内容:</label>
                <div>{{ form.content }}</div>
            </div>
            <button>返回</button>
            <button type="submit">提交</button>
        </form>
{% endblock %}

文章详情`article_detail.html`:

{% extends 'base.html' %}

{% block content %}
    <h1>{{ article.title }}</h1>
    <div>
      <span> {{ article.pub_date }}</span>
      <a href="#"><i></i> </a>
      <a href="#"><i></i> </a>
      <a href="#"><i></i> </a>
    </div>
    <p>{{ article.content }}</p>
    <a href="#">上一篇</a>
    <a href="#">下一篇</a>
{% endblock %}

9.创建`mysite/templates/base.html`基础模板,用于bootstrap美化页面:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>示例网站</title>
  <!-- CSS -->
  <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.2/css/bootstrap.min.css">
</head>
<body>
    <nav>
    <div>
      <a href="/">示例网站</a>
      <div id="navbarScroll">
        <ul style="max-height: 100px;">
          <li><a href="/">主页</a></li>
          <li><a href="#">移动</a></li>
          <li><a href="#">铁通</a></li>
          <li><a href="#">IDC</a></li>
          <li><a href="#">信安</a></li>
          <li><a href="#">政企云</a></li>
        </ul>
        <form>
          <input type="search" placeholder="输入关键字" aria-label="Search">
          <button type="submit">search</button>
        </form>
      </div>
      </div>
    </nav>
  <div>
    {% block content %}
    {% endblock %}
  </div>
</body>
</html>

10.在 `mysite/urls.py` 文件中配置路由:

from django.urls import path
from blog.views import article_create, article_list, article_detail

urlpatterns = [
    path('', article_list, name='article_list'),
    path('create/', article_create, name='article_create'),
	path('detail/<int:article_id>/', article_detail, name='article_detail'),

]

11.运行Django开发服务器来查看的网站:

python manage.py runserver

在浏览器中访问`http://127.0.0.1:8000/`,你应该可以看到文章列表页面。

转载请注明:零五宝典 » 使用Python的Django框架制作简单的文章发布系统(mysql+bootstrap)