第一步:下载mysql驱动

cmd进入创建好的django项目目录:然后使用下面的命令创建一个项目testdj。

 sudo /usr/lib/python3/dist-packages/django/bin/django-admin.py startproject testdj
然后创建一个应用testapp:
sudo /usr/lib/python3/dist-packages/django/bin/django-admin.py startapp testapp

第二步:在settings.py中配置mysql连接参数(没有mysql的先装mysql)

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': '数据库名(你得先在mysql中创建数据库)',
    'USER':'mysql用户名(如root)',
    'PASSWORD':'密码(如123456789)',
    'HOST':'域名(127.0.0.1或localhost)',
    'PORT':'端口号(3306)',
  }
}

第三步:在models.py中创建model类

from django.db import models
# Create your models here. 类似于MVC架构中的Model
class Article(models.Model):
  title = models.CharField(max_length=60,default='title')
  content = models.TextField(null=True)
第四步:根据model类创建数据库表

1、cmd进入django项目路径下

2、Python manage.py migrate #创建表结构,非model类的其他表,django所需要的

3、python manage.py makemigrations app名 #做数据迁移的准备

如:python manage.py makemigrations myblog myblog是我项目中的app名字

4、python manage.py migrate # 执行迁移,创建medel表结构

第五步:开始写代码吧

首先说下需求,就是在代码里向MySQL中插入一条记录并显示到页面

1、在templates下新建一个模板,其实就是页面,如index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h2> {{article.title}}</h2>
内容:{{ article.content }}
</body>
</html>
使用{{ }}在页面进行数据显示,这里看下就明白

2、配置URL

1、在项目下的urls.py(注意是项目下的urls.py)配置url映射:

from django.conf.urls import url,include
from django.contrib import admin
#根url配置
urlpatterns = [
  #url(页面正则,响应的方法名称)
  url(r'^admin/', admin.site.urls),
  url(r'^myblog/',include('myblog.urls')),
]
这里注意有一个include('myblog.urls')是我们接下来要配置的二级url,在app下的urls.py中配置
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
  #url(页面正则,响应的方法名称) ^index$:表示要以index开始和结束,正则约束
  url(r'^index/$',views.index),
]
现在一个路径为'localhost:8000/myblog/index/'的访问路径就配好了,url(r'^index/$',views.index)就表示最终/myblog/index/这个路径由views.py中的index方法来响应。

3、写响应函数:如像数据中插入一个数据,并显示在页面上

from django.shortcuts import render
from django.http import HttpResponse
from myblog.models import Article
# Create your views here.
def index(request):
  article = Article(title='标题',content='内容!')
  article.save()
  return render(request,'index.html',{'article':article}
第六步:运行项目

我这里使用的pycharm,点击运行按钮即可,没有pycharm的可使用:

python3 manage.py runserver 0.0.0.0:8000
 
来开启服务器,然后咋浏览器输入http://localhost:8000/myblog/index/, 打完收工!

提交表单例子:

newarticle.html in testapp/templates 文件夹

1 <html>
  2         <head>
  3                 <meta charset = "UTF-8">
  4                 <title>新添加一篇文章</title>
  5         </head>
  6         <body>
  7                 <form method="POST">
  8                         {% csrf_token %}
  9                         标题:<input type="text" name="articletitle" value="" /><br/>
 10                         作者:<input type="text" name="author" value="" /><br/>
 11                         文章内容:<textarea name="content" clos="100" rows="10" wrap="true"></textarea><br/>
 12                         <input type="submit" value="提交" />
 13                 </form>
 14         </body>
 15 </html>

testapp/views.py:

1 #__*__ encoding:UTF-8 __*__
  2 from django.shortcuts import render
  3 from django.http import HttpResponse
  4 from testapp.models import Article
  5
  6 # Create your views here.
 12
 13 def newarticle(request):
 14     if request.method == "GET":
 15         return render(request,'newarticle.html')
 16     if request.method == "POST":
 17         print(request)
 18         articletitle = request.POST.get('articletitle')
 19         content = request.POST.get('content')
 20         author = request.POST.get('author')
 21         article = Article(title=articletitle,content=content,author=author)
 22         article.save()
 23         return render(request,'index.html',{'article':article})

urls.py in testapp:

from django.conf.urls import url
  2 from django.contrib import admin
  3 from . import views
  4 urlpatterns = [
  5         url(r'^index/$',views.index),
  6         url(r'^newarticle/$',views.newarticle),
  7         ]

urls.py under testdj/ folder:

from django.conf.urls import url,include

from django.contrib import admin

urlpatterns = [

url(r'^admin/', admin.site.urls),

url(r'^testapp/',include('testapp.urls')),

]

settings.py under testdj/ folder:

set ALLOWED_HOSTS  with  '*' for all ipaddresses and hostname, or set it with a special ipddress or hostname

ALLOWED_HOSTS = ['*']

or

ALLOWED_HOSTS = ['www.abyee.com']

For deploy on apache server:

also need to edit the wsgi.py file under project folder:

here is /usr/lib/djangotest/testdj/testdj/wsgi.py

code:

import os
from os.path import dirname,abspath
import sys
from django.core.wsgi import get_wsgi_application
project_dir = dirname(dirname(abspath(__file__)))

sys.path.insert(0,project_dir)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testdj.settings")

application = get_wsgi_application()

原文:https://www.jb51.net/article/118896.htm

最新文章

  1. PHP 的 foreach
  2. web页面之响应式布局
  3. POJ 1066 Treasure Hunt (线段相交)
  4. WPF绑定xml数据源
  5. python实现Linux启动守护进程
  6. 墨菲定律-Murphy&#39;s Law (转载)
  7. JS编程常识
  8. Selenium2学习-001-Selenium2 WebUI自动化Java开发 Windows 环境配置
  9. Poj2420 A Star not a Tree? 模拟退火算法
  10. Oracle 自己主动诊断资料档案库 (ADR)、自己主动诊断工作流、ADRCI工具
  11. hdu 3923 Invoker
  12. HDU5739-Fantasia(tarjan求割点)
  13. maven项目下tomcat直接启动不了(LifecycleException)。报错如下截图
  14. c# 無彈窗调用打印机
  15. 多线程下载 HttpURLConnection
  16. hdu1561(树形背包)
  17. C#基础笔记---浅谈XML读取以及简单的ORM实现
  18. 英语学习APP的案例分析
  19. clamwin + 拖拽查毒+右键查毒
  20. python在读取文件时出现 &#39;gbk&#39; codec can&#39;t decode byte 0x89 in position 68: illegal multibyte sequence

热门文章

  1. npm手册
  2. 在Linux下如何使用openssl生成RSA公钥和私钥对
  3. Canvas Demo
  4. asp.net 去掉小数点后面多余的0
  5. luogu P2327 [SCOI2005]扫雷
  6. RNA-seq workflow
  7. 【转】基于Jenkins实现持续集成【持续更新中】
  8. springmvc &lt;mvc:default-servlet-handler/&gt; &amp; &lt;mvc:annotation-driven&gt;
  9. 2018-2019-2 网络对抗技术 20165335 Exp3 免杀原理与实践
  10. 20175208『Java程序设计』课程 结对编程练习_四则运算