我在 Django 中,修改创建的一个 Django project:
修改 Settings.py 文件,连接到数据库:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'testdb',
'USER': 'it',
'PASSWORD': 'P@ssw0rd',
'HOST': '192.168.1.10',
'PORT': 3306,
}
}
然后创建一个 App:
修改 models.py:
from django.db import models
# Create your models here.
class HostInfo(models.Model):
Item = models.IntegerField()
Model = models.CharField(max_length=40)
OS = models.CharField(max_length=40)
Host_Name = models.CharField(max_length=40)
IP_Address = models.GenericIPAddressField()
SN = models.CharField(max_length=40)
修改 Settings.py 中的 App 信息,把新建的 App 添加进去:
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
然后中 Terminal 中运行命令,在数据库中创建了对应的表:
C:\Django\mysite>python manage.py makemigrations polls
C:\Django\mysite>python manage.py migrate
然后创建了 admin 的账号和密码,进入 admin 页面后,想表中添加了数据,并且可以通过在 mysql 中可以看到:
mysql> select * from polls_hostinfo;
+----+------+--------------+----------+---------------+--------------+-----+
| id | Item | Model | OS | Host_Name | IP_Address | SN |
+----+------+--------------+----------+---------------+--------------+-----+
| 1 | 1 | DL 380 Gen 8 | ESXi 7.0 | VSVR01.sh.dto | 192.168.1.51 | 1MG |
+----+------+--------------+----------+---------------+--------------+-----+
1 row in set (0.00 sec)
我现在想通过一个页面去显示这个表的信息:
修改 views.py 文件:
from django.shortcuts import render
# Create your views here.
from .models import HostInfo
def show(request):
info = HostInfo.objects.all()
return render(request, "show.html", {"info":"info"})
在 App 目录下创建一个 templates 目录,并在该目录下创建了一个 show.html 文件,并修改内容:
{% for i in info%}
<tb>{{i.Item}}</tb>
<tb>{{i.Model}}</tb>
<tb>{{i.OS}}</tb>
<tb>{{i.Host_Name}}</tb>
<tb>{{i.IP_Address}}</tb>
<tb>{{i.SN}}</tb>
{% endfor %}
修改 urls.py 文件:
from django.urls import path
from . import views
urlpatterns = [
path("", views.show, name="show"),
]
修改 project 的 urls.py 文件:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("pulls/", include("polls.urls")),
path('admin/', admin.site.urls),
]
但我在浏览器中输入 http://127.0.0.1:8000/pulls/ 返回的是一个空白的页面,这个是怎么回事?