Django搭建第一个网站

Django搭建MyOne过程记录

接触django也有一段时间,因为期末考试忙也没有写博客~
这几天打算把自己写的练手项目重头梳理一遍部署到云端~
就把过程记录下来啦
使用django1.10 python2.7

0.前言

Tango with Django 中文文档: http://hackerxu.com/Twd/
所有网站素材均来源与网络,仅供个人学习使用。
素材来自于《One.一个》

1.新建一个Django项目

使用的编译器是pycharm
生成之后:
init.py:这是一个空的脚本,用来告诉Python编译器这个目录是一个Python包.
settings.py:用来存储Django项目设置的文件.
urls.py:用来存储项目里的URL模式.
wsgi.py:用来帮助你运行开发服务,同时可以帮助部署你的生产环境.
在项目里还有一个叫做manage.py的文件.这个文件是我们开发项目时经常使用的文件,它为我们提供了一系列的Django命令.
例:python manage.py runserver

创建名字叫One的应用.在你的Django项目的目录里,运行如下命令:
$ python manage.py startapp one
这个命令在你的项目根目录里创建了一个新的名叫one的目录 - 这里面包含了5个Python脚本.
init.py,和我们前面说过的功能一样.
models.py,一个存储你的应用中数据模型的地方 - 在这里描述数据的实体和关系.
tests.py,存储你应用的测试代码.
views.py,在这里处理用户请求和响应.
admin.py,在这里你可以向Django注册你的模型,它会为你创建Django的管理界面.

2.配置

规划如图,首页用来展示最近的图文。
所有的图文已经爬取下来放入数据库中,这一步不做详细描述啦。

先改setting配置:

[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'one'
]
# 数据库
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'webone',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
'CHARSET': 'utf8',
'TEST_CHARSET': 'utf8',
'TEST_COLLATION': 'utf8_general_ci',
}
}
# 语言和静媒
LANGUAGE_CODE = 'zh_Hans'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/' # You may find this is already defined as such.

TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = [
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
TEMPLATE_PATH,
]

STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static')

STATICFILES_DIRS = (
STATIC_PATH,
('css', os.path.join(STATIC_ROOT, 'css').replace('\\', '/')),
('js', os.path.join(STATIC_ROOT, 'js').replace('\\', '/')),
('images', os.path.join(STATIC_ROOT, 'images').replace('\\', '/')),
('upload', os.path.join(STATIC_ROOT, 'upload').replace('\\', '/')),
)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Absolute path to the media directory

myone url 添加: url(r’^’, include(‘one.urls’)), # ADD THIS NEW TUPLE!

3.生成models

[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from __future__ import unicode_literals

from django.db import models
import sys

reload(sys)
sys.setdefaultencoding('utf8')


class AuthGroup(models.Model):
name = models.CharField(unique=True, max_length=80)

class Meta:
managed = False
db_table = 'auth_group'


class AuthGroupPermissions(models.Model):
group = models.ForeignKey(AuthGroup, models.DO_NOTHING)
permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)

class Meta:
managed = False
db_table = 'auth_group_permissions'
unique_together = (('group', 'permission'),)


class AuthPermission(models.Model):
name = models.CharField(max_length=255)
content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING)
codename = models.CharField(max_length=100)

class Meta:
managed = False
db_table = 'auth_permission'
unique_together = (('content_type', 'codename'),)


class AuthUser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.IntegerField()
username = models.CharField(unique=True, max_length=150)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.CharField(max_length=254)
is_staff = models.IntegerField()
is_active = models.IntegerField()
date_joined = models.DateTimeField()

class Meta:
managed = False
db_table = 'auth_user'


class AuthUserGroups(models.Model):
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
group = models.ForeignKey(AuthGroup, models.DO_NOTHING)

class Meta:
managed = False
db_table = 'auth_user_groups'
unique_together = (('user', 'group'),)


class AuthUserUserPermissions(models.Model):
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
permission = models.ForeignKey(AuthPermission, models.DO_NOTHING)

class Meta:
managed = False
db_table = 'auth_user_user_permissions'
unique_together = (('user', 'permission'),)


class Daily(models.Model):
id = models.IntegerField(primary_key=True)
hpcontent_id = models.CharField(max_length=11, blank=True, null=True)
hp_title = models.CharField(max_length=255, blank=True, null=True)
author_id = models.IntegerField(blank=True, null=True)
hp_img_url = models.CharField(max_length=255, blank=True, null=True)
hp_img_original_url = models.CharField(max_length=255, blank=True, null=True)
hp_author = models.CharField(max_length=255, blank=True, null=True)
ipad_url = models.CharField(max_length=255, blank=True, null=True)
hp_content = models.CharField(max_length=800, blank=True, null=True)
hp_makettime = models.CharField(max_length=255, blank=True, null=True)
hide_flag = models.CharField(max_length=255, blank=True, null=True)
last_update_date = models.CharField(max_length=255, blank=True, null=True)
web_url = models.CharField(max_length=255, blank=True, null=True)
wb_img_url = models.CharField(max_length=255, blank=True, null=True)
image_authors = models.CharField(max_length=255, blank=True, null=True)
text_authors = models.CharField(max_length=255, blank=True, null=True)
image_from = models.CharField(max_length=255, blank=True, null=True)
text_from = models.CharField(max_length=255, blank=True, null=True)
content_bgcolor = models.CharField(max_length=255, blank=True, null=True)
maketime = models.CharField(max_length=255, blank=True, null=True)
praisenum = models.IntegerField(blank=True, null=True)
sharenum = models.IntegerField(blank=True, null=True)
commentnum = models.IntegerField(blank=True, null=True)
template_category = models.CharField(max_length=255, blank=True, null=True)

class Meta:
managed = False
db_table = 'daily'


class DjangoAdminLog(models.Model):
action_time = models.DateTimeField()
object_id = models.TextField(blank=True, null=True)
object_repr = models.CharField(max_length=200)
action_flag = models.SmallIntegerField()
change_message = models.TextField()
content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING, blank=True, null=True)
user = models.ForeignKey(AuthUser, models.DO_NOTHING)

class Meta:
managed = False
db_table = 'django_admin_log'


class DjangoContentType(models.Model):
app_label = models.CharField(max_length=100)
model = models.CharField(max_length=100)

class Meta:
managed = False
db_table = 'django_content_type'
unique_together = (('app_label', 'model'),)


class DjangoMigrations(models.Model):
app = models.CharField(max_length=255)
name = models.CharField(max_length=255)
applied = models.DateTimeField()

class Meta:
managed = False
db_table = 'django_migrations'


class DjangoSession(models.Model):
session_key = models.CharField(primary_key=True, max_length=40)
session_data = models.TextField()
expire_date = models.DateTimeField()

class Meta:
managed = False
db_table = 'django_session'


class RangoCategory(models.Model):
name = models.CharField(unique=True, max_length=128)

class Meta:
managed = False
db_table = 'rango_category'


class RangoPage(models.Model):
title = models.CharField(max_length=128)
url = models.CharField(max_length=200)
views = models.IntegerField()
category = models.ForeignKey(RangoCategory, models.DO_NOTHING)

class Meta:
managed = False
db_table = 'rango_page'


4.编写view

[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# coding=utf-8
import sys

from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
from django.core.paginator import Paginator
from django.shortcuts import render

from models import Daily

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)


def index(request):
# Construct a dictionary to pass to the template engine as its context.
# Note the key boldmessage is the same as in the template!

# Return a rendered response to send to the client.
# We make use of the shortcut function to make our lives easier.
# Note that the first parameter is the template we wish to use.

dailylist = Daily.objects.order_by('-id').all()[:5] # 查询所有的信息
print(type(dailylist)) # 打印结果类型与结果值
for s in dailylist:
print (s.hp_title.decode('utf-8'))
context_dict = {'content': dailylist}

return render(request, 'one/index.html', context_dict)


def about(request):
# Construct a dictionary to pass to the template engine as its context.
# Note the key boldmessage is the same as in the template!
context_dict = {'boldmessage': "I am bold font from the context"}

# Return a rendered response to send to the client.
# We make use of the shortcut function to make our lives easier.
# Note that the first parameter is the template we wish to use.

return render(request, 'one/about.html', context_dict)


def search(request):
result_list = []
limit = 5 # 每页显示的记录数

if request.method == 'POST':
query = request.POST['query'].strip()

if query:
# Run our Bing function to get the results list!
result_list = Daily.objects.order_by('-id').filter(hp_content__contains=query)
paginator = Paginator(result_list, limit) # 实例化一个分页对象

page = request.GET.get('page') # 获取页码
try:
result_list = paginator.page(page) # 获取某页对应的记录
except PageNotAnInteger: # 如果页码不是个整数
result_list = paginator.page(1) # 取第一页的记录
except EmptyPage: # 如果页码太大,没有相应的记录
result_list = paginator.page(paginator.num_pages) # 取最后一页的记录

else:
query = request.GET.get('query')
result_list = Daily.objects.order_by('-id').filter(hp_content__contains=query)
paginator = Paginator(result_list, limit) # 实例化一个分页对象

page = request.GET.get('page') # 获取页码
try:
result_list = paginator.page(page) # 获取某页对应的记录
except PageNotAnInteger: # 如果页码不是个整数
result_list = paginator.page(1) # 取第一页的记录
except EmptyPage: # 如果页码太大,没有相应的记录
result_list = paginator.page(paginator.num_pages) # 取最后一页的记录

return render(request, 'one/search.html', {'result_list': result_list, 'query': query})

5.添加映射

one/urls

[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^about', views.about, name='about'),
url(r'^search', views.search, name='search'),
]




###myone/urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('one.urls')), # ADD THIS NEW TUPLE!

]

6.源码

https://github.com/ZhangMengRou/MyOne

效果图:
img