Django学习笔记一:创建新App及其常用命令

清明节假期,正是读书、学习的好时候;别人都出去玩了,然而我仍然在“学习”。之前一直对Django很感兴趣(因为很多人提到了它,而我也有打算在未来用Python重构PHP做的系统),因此就学习了一下

创建新的项目

1
django-admin.py startproject my_project

创建新的App

1
2
# 在Django项目(my_project)的根目录下执行
python3 manage.py startapp my_app

启动Django中的开发服务器

1
2
3
4
5
6
# make new migrations
python3 manage.py makemigrations
# apply all migrations
python3 manage.py migrate
# run server
python3 manage.py runserver

创建models

1
2
3
4
5
6
7
8
9
10
class App1(models.Model):
title = models.CharField(max_length=100)
category = models.CharField(max_length=50, blank=True)
date_time = models.DateTimeField(auto_now_add=True)

def __unicode__(self):
return self.title

class Meta:
ordering = ['-date_time']

进入Django中的交互式shell

1
2
3
4
5
6
7
8
9
10
11
12
13
python3 manage.py shell
from app1.models import App1
# create(增加操作)
App1.objects.create(title='title',category='category1')
# allget(查看操作)
App1.objects.all()
App1.objects.get(id=1)
# update(修改操作)
demo = App1.objects.get(id=1)
demo.title
demo.title='title2'
# delete(删除操作)
demo.delete()

创建一个超级用户

1
2
python3 manage.py createsuperuser
# 输入http://127.0.0.1:8000/admin登录后台

数据库信息的增加和删除,admin.py中增加代码

1
2
from article.models import App1
admin.site.register(App1)

Views和URL操作

1
2
3
4
5
6
# views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello World, Django")
# urls.py
url(r'^$', 'app1.views.home')

URL传参

1
2
3
4
5
# views.py
def detail(request, number):
return HttpResponse("The number is %s." % number)
# urls.py
url(r'^([0-9]+)/', 'app1.views.detail', name='detail')

URL传参查询数据库

1
2
3
4
5
6
7
# views.py
def database(request, args):
post = App1.objects.all()[int(args)]
str = ("title = %s, category = %s, date_time = %s" % (post.title, post.category, post.date_time))
return HttpResponse(str)
# urls.py
url(r'^id/([0-9])+/', 'article.views.database', name='database'),

将代码上传到Github

1
2
3
4
5
6
7
8
9
# 在github中新建仓库django-blog
# 在项目根目录下执行
git init
git remote add Django
git@github.com:ybbz/django-blog.git
git add .
git status
git commit -m "django blog init"
git pull Django master && git push Django master

Error: That port is already in use.

1
2
3
ps aux | grep -i manage
kill -9 ****
python3 manage.py runserver
八宝粥 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!