Django的视图类读取数据

一 新建模型

from django.db import models
from django.contrib.auth.models import User
from slugify import slugify

class Course(models.Model):
    user = models.ForeignKey(User, related_name='courses_user')
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    overview = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created',)

    def save(self, *args, **kargs):
        self.slug = slugify(self.title)
        super(Course, self).save(*args, **kargs)

    def __str__(self):
        return self.title

二 迁移数据库

(venv) E:\Django\mysite\mysite>python manage.py makemigrations
(venv) E:\Django\mysite\mysite>python manage.py migrate

三 编写类视图

# 引入ListView
from django.views.generic import TemplateView,ListView
from .models import Course

class AboutView(TemplateView):
    template_name = "course/about.html"

# 继承ListView
class CourseListView(ListView):
    # 被类所使用的数据模型,能够得到数据表中的所有记录
    model = Course
    # 传入模板的变量名称
    context_object_name = "courses"
    # 模板文件
    template_name = 'course/course_list.html'

四 编写模板

{% extends "base.html" %}
{% block title %}Course List{% endblock %}
{% block content %}
{% for course in courses %} {% endfor %}
序号 课程标题 讲师 发布日期
{{ forloop.counter }} {{ course.title }} {{ course.user.username }} {{ course.created }}
{% endblock %}

五 编写URL

from django.conf.urls import url
from .views import AboutView,CourseListView

urlpatterns = [
    url(r'about/$', AboutView.as_view(), name="about"),
    url(r'course-list/$', CourseListView.as_view(), name="course_list"),
]

六 测试

Django的视图类读取数据_第1张图片

你可能感兴趣的:(Django)