今天成功使自己的模型能够显示在模板上,顺序如下:
1.建立模型,解决模型建立的问题
Django在执行迁移文件时出现的错误,即当你在Pycharm下面的Terminal中输入’Python manger.py makemigrations’ 时出现以下错误:
You are trying to add a non-nullable field 'hbook' to heroinfo without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null v
alue for this column)
2) Quit, and let me add a default in models.py
- 解决方法:
删除migrations下的0001_initial.py文件,之后重新在Terminal执行python manage.py makemigrations和python manage.py migrate,重新生成迁移文件。
2.使用API来事先获知数据。再运用到视图和模板中。
C:\Users\Season\workspace2\training_system>python manage.py shell
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.14.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from myclass.models import Subject
In [2]: Subject.objects.all()
Out[2]: <QuerySet [<Subject: HR-001.培训>, <Subject: HR-002.招聘>]>
In [3]: s = Subject..objects.filter(id=1)
File "<ipython-input-3-3fdf41ec21fe>", line 1
s = Subject..objects.filter(id=1)
^
SyntaxError: invalid syntax
In [4]: s = Subject.objects.filter(id=1)
In [5]: s
Out[5]: <QuerySet []>
In [6]: s = Subject.objects.filter(Subject_id='HR-001')
In [7]: s
Out[7]: <QuerySet [<Subject: HR-001.培训>]>
3.设定myclass视图如下:
请注意Subject_list。
from django.shortcuts import render
from .models import Subject,Employee,Employee_Subject,Teacher
# Create your views here.
def index(request):
Subject_list = Subject.objects.order_by('-Subject_id').all()[:5]
context = {
'Subject_list':Subject_list}
return render(request,'myclass/index.html',context=context)
4.设定URL如下:
- training_system项目中URL
from django.contrib import admin
from django.urls import path,include
from myclass import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index, name='index'),
path('myclass/',include('myclass.urls')),
]
- myclass项目中URL
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
]
5.模板设定
建议在training_system项目中设定templates,如下:
请注意Subject_list。
<html>
<head>
<title>notice</title>
</head>
<body>
<table>
{% for item in Subject_list %}
<tr>
<td>{
{ item.Subject_id }}</td>
<td>{
{ item.subject_name }}</td>
<td>{
{ item.teacher.name }}</td>
</tr>
{% endfor %}
</table>
</body>