Django1.11.1+python3.5+Pycharm 快速搭建博客blog

时间:2020-11-29 19:19:48

1、新建Django项目

Django1.11.1+python3.5+Pycharm 快速搭建博客blog

2、测试Django 博客项目搭建是否成功:

Django1.11.1+python3.5+Pycharm 快速搭建博客blog

3、编辑代码:

3.1、修改blog.models.py:

from django.db import models
from django.contrib import admin


class BlogPost(models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
timestamp = models.DateTimeField()


class BlogPostAdmin(admin.ModelAdmin):
list_display = ('title', 'body', 'timestamp')


admin.site.register(BlogPost, BlogPostAdmin)



3.2、修改blog.views.py:

from blog.models import BlogPost
from django.template import loader,Context
from django.http import HttpResponse


def archive(request):
posts = BlogPost.objects.all()
t = loader.get_template('archive.html')
c = Context({'posts':posts})
return HttpResponse(t.render(c))

3.3、修改blog_workspace.setting.py

#应用名称配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]

#数据库连接配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangoDB',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}

3.4、修改blog_workspace.urls.py

from django.conf.urls import url
from django.contrib import admin
from blog.views import *
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^blog/$', archive),
]

4、建立网页模板

注意:请在模块blog下添加templates文件夹

4.1、编辑archive.html

{% extends "base.html" %}
{% block content %}
{% for post in posts %}
<h1>{{ post.title}}</h1>
<p>{{ post.timestamp|date:"1, F jS"}}</p>
<p>{{ post.body }}</p>
{% endfor %}
{% endblock %}

4.2、编辑base.html

<html>
<style type="text/css">
body { color: #edf; background: #453; padding: 0 5em; margin:0 }
h1 { padding: 2em; background:#675 }
h2 { color: #bf8; border-top: 1px dotted #fff; margin-top: 2em }
p { margin: 0 }
</style>
<body>
<h1>mysite.example.com</h1>
{% block content %}
{% endblock %}
</body>
</html>


5、同步数据库

Django1.11.1 +pymysql 数据库同步请参考:http://blog.csdn.net/zhouzhiwengang/article/details/72235831


6、项目运行:

"D:\Program Files (x86)\JetBrains\PyCharm 2017.1\bin\runnerw.exe" "D:\Program Files\python\python.exe" D:/user_workspace/manage.py runserver 8000
Performing system checks...

System check identified no issues (0 silenced).
May 16, 2017 - 09:51:28
Django version 1.11.1, using settings 'user_workspace.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.


补充说明:如何添加Python 默认数据库管理员信息,请参考: http://www.runoob.com/django/django-admin-manage-tool.html

项目源代码: