Django简单项目示例,数据库使用自带的sqlite3

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/查看效果
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xuerba

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值