django初探

django 
django基于MTV模式
安装django
-pip3 install django
#创建django工程
django-admin.exe startproject 工程名称
工程目录结构(例如mysite)
mysite
-mysite #对整个程序进行配置
-init.py
-settings.py #配置文件
-url.py #URL对应关系
-wsgi.py #遵循WSGI规范
-manage.py #管理django程序:
-python manage.py
-python manage.py startapp xx
-python manage.py makemigrations
-python manage.py migrate
#运行django功能
python manage.py runserver 121.0.0.1:8001
#创建app
python manage.py startapp cmdb
app:
migrations 数据修改表结构
admin django为我们提供的后台管理
apps 配置当前app
models orm,写指定的类 通过命令可以创建数据库结构
tests 单元测试
views 业务代码
1.配置模板目录
settings.py文件
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,"templates")],#添加模板路径templates
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
2.配置静态目录
settings.py文件
STATICFILES_DIRS = (
os.path.join(BASE_DIR,"/static"),#添加静态文件路径
)
3.settings.py文件中middleware注释
'django.middleware.csrf.CsrfViewMiddleware',一项应该注释掉,这样提交表单就不会出错
4.定义路由规则
url.py
5.定义视图函数
app下views.py
def func(request):
#request.method#用户提交方式(分为POST与GET两种)
#reques.GET.get("nid",None) 例如可通过(http://127.0.0.1/home?nid=123&name=alex)
#reques.POST.get("",None)

#return HttpResponse("字符串")
#return render(request,"html文件路径")
#return redirect("URL路径")#不能添加.html后缀名
6.模板渲染
特殊的模板语言
-- {{ 变量名 }}
def home(request):
return render(request, "login.html",{"error_msg":error_msg})#{{error_msg}}会被error_msg代替
index.html
<html>
<body>
<span style="color:red;">{{error_msg}}</span>
</body>
</html>
-- For循环
def home(request):
return render(request, "login.html",{"current_user":"alex",""user_list":["alex","eric"]})
index.html
<html>
<body>
<span style="color:red;">{{current_user}}</span>
<div>
<ul>
{% for row in user_list %}
<li>{{ row }}</li>
{% endfor %}
</ul>
</div>
</body>
</html>
-- 条件
def home(request):
return render(request, "login.html",{"age":18,""current_user":"alex",""user_list":["alex","eric"]})
index.html
<html>
<body>
<span style="color:red;">{{current_user}}</span>
<div>
{% if age > 10 %}
<a></a>
{% else %}
<a></a>
{% endif %}
</div>
</body>
</html>
原文地址:https://www.cnblogs.com/cansun/p/8593421.html