pycharm创建Django项目以及运行过程(以一个简易博客系统为例)

一、条件准备
需要事先准备的就是python3、Django2以及pycharm和MySQL的安装,建议安装MySQL5.7及以上的版本,这里我主要讲的是Django项目的创建以及执行过程,安装过程我这里就不再讲解了。
二、创建过程
1、Django项目创建:
在pycharm中,File→New Project→Django,如下如中所示
在这里插入图片描述
在这里插入图片描述
create之后,稍等片刻后会创建成功,项目的目录如下:
在这里插入图片描述
接下来,我为大家介绍一下项目目录中各个文件的作用:
①seetings.py:见其名知其意,这是项目配置文件
②urls.py:项目路由文件
③manage.py:项目管理文件

2、运行Django项目
点击任务栏的绿色三角
在这里插入图片描述
当下方出现如下图所示时
在这里插入图片描述
点击红框中的地址,如果在浏览器中出现如下情况,则表明项目创建的没毛病!
在这里插入图片描述
3、Django应用的创建
打开Terminal终端(在pycharm的右下角)使用如下命令创建Django应用

#python manage.py startapp 应用名
#例如
python manage.py startapp myapp

然后回车,如果没有报错,刷新项目目录后发现出现“myapp”这个文件夹,文件夹的目录如下图所示,接下来我将讲解Django应用里每个文件的作用:
在这里插入图片描述
①admin.py:定义Admin模块管理对象的地方
②apps.py:声明应用的地方
③models.py:定义应用模型的地方
④tests.py:编写应用测试用例的地方
⑤views.py:视图处理的地方
4、Django 的第一个应用实例–Hello World
4. 1 在views.py中输入以下代码

from django.http import HttpResponse

def hello(request):
    return HttpResponse("hello world")

4.2 Django路由的设置
在myapp中新建urls.py文件,然后输入以下代码:

from django.urls import path
import myapp.views

urlpatterns = [
    path('hello', myapp.views.hello),
]

然后在untitled4\urls.py中加入以下代码

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app/', include('myapp.urls')),
]

4.3在settings.py文件中找到INSTALLED_APPS配置项,在里面加入如下代码

'myapp',

接下来启动项目,启动成功后,在浏览器地址端输入http://127.0.0.1:8000/app/hello发现网页上输出了hello world

5、博客系统正式进入开发阶段,首先是模型的创建,在myapp\models.py中输入以下代码:

class Article(models.Model):
    # 文章的唯一ID
    article_id = models.AutoField(primary_key=True)
    # 文章标题
    title = models.TextField()
    # 文章的摘要
    brief_content = models.TextField()
    # 文章的主要内容
    content = models.TextField()
    # 文章的发布日期
    publish_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

然后是数据库的迁移,在此之前要进行数据库的配置,Django默认的数据库是SQLite,如果同学继续使用SQLite,可以直接略过此步,如果有使用MySQL的同学,在settings.py中,找到DATABASE,然后把原来的代码替换成以下代码:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',  # 数据库名字
        'USER': 'root',  # 账号
        'PASSWORD': '这里输入密码',  # 密码
        'HOST': '127.0.0.1',  # IP
        'PORT': '3308',  # 端口号,我的是3306,需要根据自己情况设定
    }
}

然后在Terminal终端输入命令:pip install pymysql 回车安装pymysql包,
在这里插入图片描述
表明安装成功。

完成之后在myapp_init_.py中加入以下代码:

import pymysql

pymysql.install_as_MySQLdb()

紧接着在Terminal终端输入命令:python manage.py makemigrations回车后如果报如下错误
在这里插入图片描述
那么解决方法很简单,只需要打开base.py,强行注释35、36行的代码
在这里插入图片描述
再次python manage.py makemigrations回车,还会报错
在这里插入图片描述
打开operations.py,再次强行注释145、146行的代码
在这里插入图片描述
之后python manage.py makemigrations回车,
在这里插入图片描述
然后在Terminal终端python manage.py migrate回车
在这里插入图片描述
表明迁移成功

6.Django Admin的应用
在Terminal终端python manage.py createsuperuser回车,创建超级用户
然后在myapp\models.py加入以下代码:

from django.contrib import admin

from .models import Article

admin.site.register(Article)

启动项目,然后在浏览器输入http://127.0.0.1:8000/admin然后登录刚才创建的超级用户,进入博客的后台管理界面,
在这里插入图片描述
点击Articles然后点击右上角的ADD ARTICLE可以添加文章

7、实现博客数据返回页面
7.1在myapp\view.py加入代码:

from myapp.models import Article

def article_content(request):
    article = Article.objects.all()[0]
    title = article.title
    brief_content = article.brief_content
    content = article.content
    article_id = article.article_id
    publish_date = article.publish_date
    return_str = 'title: %s, brief_content: %s, ' \
                 'content: %s, article_id: %s, publish_date: %s' % (title,
                                                                    brief_content,
                                                                    content,
                                                                    article_id,
                                                                    publish_date)
    return HttpResponse(return_str)

7.2配置路由
在myapp\urls.py中

urlpatterns = [
    path('hello', myapp.views.hello),
    path('content', myapp.views.article_content),
]

然后启动项目,浏览器地址输入http://127.0.0.1:8000/app/content,就会打印出文章相应信息
8、实现博客页面
在myapp\views.py更新代码如下

from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
from myapp.models import Article


def hello(request):
    return HttpResponse("hello world")


def article_content(request):
    article = Article.objects.all()[0]
    title = article.title
    brief_content = article.brief_content
    content = article.content
    article_id = article.article_id
    publish_date = article.publish_date
    return_str = 'title: %s, brief_content: %s, ' \
                 'content: %s, article_id: %s, publish_date: %s' % (title,
                                                                    brief_content,
                                                                    content,
                                                                    article_id,
                                                                    publish_date)
    return HttpResponse(return_str)


def get_index_page(request):
    page = request.GET.get('page')
    if page:
        page = int(page)
    else:
        page = 1
    print('page param', page)
    all_articles = Article.objects.all()
    top5_article_list = Article.objects.order_by('-publish_date')[:5]
    paginator = Paginator(all_articles, 5)
    page_num = paginator.num_pages
    print('page num', page_num)
    page_article_list = paginator.page(page)
    if page_article_list.has_next():
        next_page = page + 1
    else:
        next_page = page
    if page_article_list.has_previous():
        previous_page = page - 1
    else:
        previous_page = page

    return render(request, 'myapp/index.html',
                  {'article_list': page_article_list,
                   'page_num': range(1, page_num + 1),
                   'curr_page': page,
                   'next_page': next_page,
                   'previous_page': previous_page,
                   'top5_article_list': top5_article_list
                   }
                  )


def get_detail_page(request, article_id):
    all_articles = Article.objects.all()
    curr_article = None
    previous_index = 0
    next_index = 0
    previous_article = None
    next_article = None
    for index, article in enumerate(all_articles):
        if index == 0:
            previous_index = 0
            next_index = index + 1
        elif index == len(all_articles) - 1:
            previous_index = index - 1
            next_index = index
        else:
            previous_index = index - 1
            next_index = index + 1

        if article.article_id == article_id:
            curr_article = article
            previous_article = all_articles[previous_index]
            next_article = all_articles[next_index]
            break
    section_list = curr_article.content.split('\n')
    return render(request, 'myapp/detail.html',
                  {'curr_article': curr_article,
                   'section_list': section_list,
                   'previous_article': previous_article,
                   'next_article': next_article
                   }
                  )

更新myapp\urls.py

from django.urls import path, include
import myapp.views

urlpatterns = [
    path('hello', myapp.views.hello),
    path('content', myapp.views.article_content),
    path('index', myapp.views.get_index_page),
    # path('detail', myapp.views.get_detail_page),
    path('detail/<int:article_id>', myapp.views.get_detail_page)
]

在myapp新建文件夹templates,在templates中新建文件夹myapp,然后新建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试主页</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
</head>
<body>
<div class="container page-header">
    <h1>Django test code
        <small>for test</small>
    </h1>
</div>
<div class="container page-body">
    <div class="col-md-9" role="main">
        <div class="body-main">
            {% for article in article_list %}
                <div>
                    <h2><a href="/app/detail/{{ article.article_id }}">{{ article.title }}</a></h2>
                    <p>
                        {{ article.brief_content }}
                    </p>
                </div>
            {% endfor %}
        </div>
        <div class="body footer">
            <div class="col-md-4 col-md-offset-3">
                <nav aria-label="Page navigation">
                    <ul class="pagination">
                        <li>
                            <a href="/app/index?page={{ previous_page }}" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                        {% for num in page_num %}
                            <li><a href="/app/index?page={{ num }}">{{ num }}</a></li>
                        {% endfor %}

                        <li>
                            <a href="/app/index?page={{ next_page }}" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>

    </div>
    <div class="col-md-3" role="complementary">
        <div>
            <h2>最新文章</h2>
            {% for article in top5_article_list %}
                <h4><a href="/app/detail/{{ article.article_id }}">{{ article.title }}</a></h4>
            {% endfor %}
        </div>
    </div>

</div>
</body>
</html>

和detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试详情页面</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
</head>
<body>
<div class="container page-header">
    <h1>{{ curr_article.title }}
    </h1>
</div>
<div class="container page-body">
    <div class="body-main">
        <div>
            {% for section in section_list %}
                <p>{{ section }}</p>
            {% endfor %}
        </div>
        <div>
            <nav aria-label="...">
                <ul class="pager">
                    <li><a href="/app/detail/{{ previous_article.article_id }}">上一篇:{{ previous_article.title }}</a>
                    </li>
                    <li><a href="/app/detail/{{ next_article.article_id }}">下一篇:{{ next_article.title }}</a></li>
                </ul>
            </nav>
        </div>


    </div>

</div>
</body>
</html>

此时,myapp的目录应该如下图所示
在这里插入图片描述
到这里,博客的主页面和文章详情页面基本开发完成。
三、执行
启动项目,在浏览器地址栏输入http://127.0.0.1:8000/admin,登录超级用户,在后台添加几篇文章,建议多添加一些,我这里已经事先添加过了
在这里插入图片描述
紧接着访问http://127.0.0.1:8000/app/index,会在网页前端展示你所添加的所有文章,右侧的最新文章的顺序是按时间的倒叙排列,也就是最先添加的文章在第一篇,点击每篇文章,就会跳转至此文章的详情界面,在主页面的最底部,有页码展示,可以点击进行跳转。在这里插入图片描述
在每篇文章的详情页面下方,还有上一篇或者下一篇文章的跳转按钮
在这里插入图片描述
到这里,使用Django开发的简易博客系统就全部完成。各位同学一定要亲自动手去把代码敲出来,这样的练习才会有效果。最后,强烈建议同学们阅读了解一下Django的底层源码,了解它的实现原理以及过程,毕竟要知其然,还要知其所以然。

感谢大家的阅读。

  • 8
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值