Django簡單項目示例,數據庫使用自帶的sqlite3
1.新建djang項目django-admin.py startproject django_test
2.設置settings.py
#設置主機IP,設置為*允許任何IP
ALLOWED_HOSTS = ['*']
#修改TEMPLATES中的DIRS APPDIRS
'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/'),],
'APP_DIRS': False,
#新增STATIC_URL STATICFILES_DIRS,用於引用靜態文件
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
3.新建app python manage.py startapp main
,將main
加入settings.py
INSTALLED_APPS
中
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main', # 加入自己新建的app main
]
4.前端頁面編寫templates/index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>測試頁面</h1>
<table border="1px">
<thead>
<tr>
<th>姓名</th>
<th>年齡</th>
</tr>
</thead>
<tbody>
{% for i in students %}
<tr>
<th>{{ i.name }}</th>
<th>{{ i.age }}</th>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
5.後端代碼編寫main/models.py
,使用python manage.py inspectdb student
命令生錯model
from django.db import models
class Student(models.Model):
id = models.IntegerField(primary_key=True)
name = models.TextField(blank=True, null=True) # This field type is a guess.
age = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'student'
6.後端代碼編寫main/views.py
from django.shortcuts import render
from main.models import Student
def index(request):
students = Student.objects.all()
return render(request, 'index.html', {'students': students})
7.設置django_test/urls.py
from django.conf.urls import url
from django.contrib import admin
from main.views import index
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index)
]
8.訪問http://127.0.0.1:8000/index/
查看效果