#开始步骤
pip install django django-admin startproject mysite python manage.py runserver 8000 打开浏览器访问127.0.0.1:8000
# 新增url
#urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('hello/', views.hello), ] #mysite目录下新建views.py from django.shortcuts import render,HttpResponse def hello(req): return HttpResponse("hello world!")
#增加app
python manage.py startapp post # 生成 mysite/post目录和目录下 admin.py apps.py models.py tests.py views.py __init__.py # mysite/setting.py中INSTALLED_APPS增加’post‘ INSTALLED_APPS = [ ... 'post' ] #post/views.py from django.shortcuts import render,HttpResponse def index(request): return HttpResponse('post/index') #创建post/urls.py from django.urls import path from . import views urlpatterns = [ path('index', views.index,name="index"), ] #mysite/urls.py urlpatterns = [ ... path('post/', include('post.urls')), ]
#创立模型
Django将关系型的表(table)转换成为一个类(class)。而每个记录(record)是该类下的一个对象(object)。我们可以使用基于对象的方法,来操纵关系型的数据库。
#post/models.py from django.db import models class Post(models.Model): """post""" title=models.CharField(max_length=50) content=models.CharField(max_length=500) create_at=models.DateTimeField(auto_now_add=True) def __str__(self): """返回模型的字符串表示""" return self.title #命令行执行迁移 python manage.py makemigrations python manage.py migrate post #post/views.py添加 from post.models import Post def lists(request): post_list = Post.objects.all() post_str = map(str, post_list) return HttpResponse("<p>" + ' '.join(post_str) + "</p>") def create(request): post=Post(title='bb',content='bbbbbbb') post.save() return HttpResponse("<p>created bb </p>") #post/urls.py添加 urlpatterns = [ ... path('lists',views.lists,name="lists"), path('create',views.create,name="create"), ]
标签:views,django4,py,基础,models,path,import,post From: https://www.cnblogs.com/caroline2016/p/16906540.html