我的目标是将数据库中的数据打印为表格。我可以用简单的表格吗?
views.py
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.shortcuts import render
from .models import *
class IndexView(ListView):
template_name = 'Dashboard/index.html'
def get_queryset(self):
return ccc
class CourseView(DetailView):
model = Course
template_name = 'Dashboard/course.html'
class TeacherView():
def teacher(request):
return render(request, 'Dashboard/teacher.html', {'table' : User.objects.all()})
teacher.html
{% load render_table from django_tables2 %}
<!doctype html>
<html>
<head>
<title>All Teachers</title>
</head>
<body>
{% render_table table %}
</body>
</html>
urls.py
from django.urls import path
from . import views
app_name = 'Dashboard'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.CourseView.as_view(), name='detail'),
path('teacher/', views.User, name='teacher'),
]
models.py
from django.db import models
class User(models.Model):
unam = models.CharField(max_length=200)
uid = models.AutoField(primary_key=True)
umob = models.IntegerField()
umail = models.EmailField()
uimg = models.CharField(max_length=1000, default='null')
def __str__(self):
return self.unam
settings.py
INSTALLED_APPS = [
'django_tables2',
'Dashboard.apps.DashboardConfig',
我的目标是将数据库中的数据打印为表格。我可以用简单的表格吗?
答案 0 :(得分:0)
您的views.py内部没有“用户”视图。
path('teacher/', views.User, name='teacher')
但是是TeacherView。我建议您使用模板视图并定义用户上下文 https://docs.djangoproject.com/en/2.0/ref/class-based-views/base/#templateview
如果我建议的话,请不要在模型属性的前面加上“ u”前缀。用户模型已经可以说明一切。即使将其命名为“ User”,它在某些时间点上也可能与Django的Auth User Model冲突。
最后但并非最不重要的一点是,如果可以的话,尽量避免*
答案 1 :(得分:0)
按如下所示更改views.py
from django.views import View
class TeacherView(View):
def get(self, request):
return render(request, 'Dashboard/teacher.html', {'table' : User.objects.all()})
现在还可以如下更改urlpatterns
path('teacher/', views.TeacherView.as_view(), name='teacher')
我希望这对您有用。