用户 | 密码 |
---|---|
{{d.username}} | {{d.password}} |
Python版本3.5,django版本1.10
1 新建项目
django-admin.py startproject website1
2 启动服务器,查看是否正常
manage.py runserver
3 进入工程website1一级文件夹下新建apppython 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
首页
数据录入
所有数据
数据录入
showData.html
所有数据
用户
密码
{% for d in alldata %}
{{d.username}}
{{d.password}}
{% endfor %}
遇到的错误:
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 %}”