Django 创建新App及其常用命令的实现方法
创建新的项目
django-admin.py startproject my_project
创建新的App
# 在Django项目(my_project)的根目录下执行 python3 manage.py startapp my_app
启动Django中的开发服务器
# make new migrations python3 manage.py makemigrations # apply all migrations python3 manage.py migrate # run server python3 manage.py runserver
创建models
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
python3 manage.py shell from app1.models import App1 # create(增加操作) App1.objects.create(title='title',category='category1') # all和get(查看操作) App1.objects.all() App1.objects.get(id=1) # update(修改操作) demo = App1.objects.get(id=1) demo.title demo.title='title2' # delete(删除操作) demo.delete()
创建一个超级用户
python3 manage.py createsuperuser # 输入http://127.0.0.1:8000/admin登录后台
数据库信息的增加和删除,admin.py中增加代码
from article.models import App1 admin.site.register(App1)
Views和URL操作
# views.py from django.http import HttpResponse def home(request): return HttpResponse("Hello World, Django") # urls.py url(r'^$', 'app1.views.home')
URL传参
# 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传参查询数据库
# 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
# 在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.
ps aux | grep -i manage kill -9 **** python3 manage.py runserver
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。