1. 程式人生 > >【django2】模型 django 1.10 + sqlite3

【django2】模型 django 1.10 + sqlite3

Python版本3.5,django版本1.10


1 新建專案

    django-admin.py startproject website1

2 啟動伺服器,檢視是否正常

    manage.py runserver

3 進入工程website1一級資料夾下新建app

    python manage.py startapp appdemo

4 將新建立的app加入工程中

    修改 website1/website1/settings.py的INSTALL_APPS,將app名稱加入該元組中。

5 修改website1/urls.py檔案

from django.conf.urls import url
from django.contrib import admin
from appdemo import views as appdemo_views

urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^$', appdemo_views.index, name='index'),
    url(r'^addUser/', appdemo_views.addUser, name='addUser'),
    url(r'^saveInfo/', appdemo_views.saveInfo, name='saveInfo'),
    url(r'^queryAll/', appdemo_views.queryAll, name='queryAll'),
]
    四個URL是首頁,新增資料,儲存資料,查詢所有資料四個連結,與views中四個函式對應。

6 修改appdemo/views.py檔案,新增四個函式

from django.shortcuts import render
from .models import UserInfo

# Create your views here.
def index(request):
	return render(request, 'appdemo/index.html')

def addUser(request):
	return render(request, 'appdemo/addUser.html')

def saveInfo(request):
	username = request.POST['username']
	password = request.POST['password']
	UserInfo.objects.create(username=username, password=password)
	return render(request, 'appdemo/index.html')

def queryAll(request):
	data = UserInfo.objects.all()
	return render(request, 'appdemo/showData.html', {'alldata':data})
    首頁和新增資料頁面都是直接返回html檔案,儲存和查詢兩個函式需要寫入或讀取資料庫,它們是通過appdemo/models.py檔案中UserInfo類實現資料庫操作。

    django自帶的資料庫API包含了查詢,排序,修改等多個函式,詳見http://www.ziqiangxuetang.com/django/django-queryset-api.html

7 在appdemo/models.py中編寫資料庫操作類UserInfo

from django.db import models

# Create your models here.
class UserInfo(models.Model):
	username = models.CharField(max_length=30)
	password = models.CharField(max_length=30)

	def __str__(self):
		return self.username+", "+self.password

8 編寫html檔案

index.html

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<title>首頁</title>
</head>
<body>
	<a href="/addUser/">資料錄入</a>
	<a href="/queryAll/">所有資料</a>
</body>
</html>

addUser.html

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<title>資料錄入</title>
</head>
<body>
	<form action="/saveInfo/" method="post">
		{% csrf_token %}
		使用者:<input name="username" type="text" ><br/>
		密碼:<input name="password" type="password" ><br/>
		<input type="submit" value="儲存" >
	</form>
</body>
</html>

showData.html

<!DOCTYPE html>
<html>
<head lang="en">
	<meta charset="UTF-8">
	<title>所有資料</title>
	<style>
		table, td{font:100% Arial, Helvetica, sans-serif; }
		table{width:100%;border-collapse:collapse;margin:1em 0;}
		th, td{text-align:left;padding:.5em;border:1px solid #fff;}
		th{background:#328aa4 url(tr_back.gif) repeat-x;color:#fff;}
		td{background:#e5f1f4;}
	</style>
</head>
<body>
<div id="container">
	<div id="content">
	<table cellspacing="0" cellpadding="0">
		<tr>
			<th>使用者</th>
			<th>密碼</th>
		</tr>
		{% for d in alldata %}
			<tr>
			<td>{{d.username}}</td>
			<td>{{d.password}}</td>
			</tr>
		{% endfor %}
	</table>
	</div>
</div>
</body>
</html>

遇到的錯誤:

1 You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. 

    解決方法:在表單的action連結後加上“/”

2 Forbidden (403) CSRF verification failed. Request aborted

    在html表單輸入部分之前加上“{% csrf_token %}”