【发布时间】:2021-01-31 17:38:09
【问题描述】:
我在将两个模型中的数据显示到单个 html 页面时遇到问题
我有两个模型 - 第一个称为 Course 和第二个称为 Lesson 好的,所以我想添加课程然后在课程中添加课程并在一个 html 页面中显示数据
models.py:
class Course(models.Model):
title = models.CharField(max_length=100,default="")
name = models.CharField(max_length=100,default="")
app_contect = RichTextField(blank=True,null=True)
app_image = models.ImageField(upload_to='images/',null=True, blank=True)
post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
post_tag = models.CharField(max_length=50,default="",choices = COURSE_SECTION)
objects = SearchManager()
slug = models.SlugField(default="",blank=True,unique=True,editable=True)
def save(self, *args, **kwargs):
if not self.id or not self.slug:
super(Course, self).save(*args, **kwargs)
self.slug = slugify(f"{self.title} {str(self.id)}")
super(Course, self).save(*args, **kwargs)
def get_image(self):
if self.app_image and hasattr(self.app_image, 'url'):
return self.app_image.url
else:
return '/path/to/default/image'
def __str__(self):
return self.name
class Meta:
ordering = ('-post_date',)
class Lesson(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
youtube_url = models.URLField()
def __str__(self):
return self.name
admin.py:
from django.contrib import admin
from blog_app.models import Course,Lesson
class InlineLessons(admin.StackedInline):
model = Lesson
class CourseAdmin(admin.ModelAdmin):
inlines = [ InlineLessons ]
admin.site.register(Lesson)
admin.site.register(Course,CourseAdmin)
那么如何将课程和课程模型中的数据显示到一个 html 页面中?
i tried do this but it's don't work , it just show data from Course model
views.py:
def course_posts(request,slug):
lesson = Lesson.objects.all()
course_posts = get_object_or_404(Course, slug=slug)
context = {'course_posts':course_posts}
return render(request,'course/course_posts_page.html', { 'course_posts': course_posts,'lesson':lesson })
html页面:
<h1 id="font_control_for_header_in_all_pages"> {{course_posts.name}} </h1>
<div id="accordion">
<div class="card">
<div class="card-header" id="headingOne">
<h5 class="mb-0 text-center">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
{{lesson.name}}
</button>
</h5>
</div>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body">
<iframe width="100%" height="400px" src="{{lesson.youtube_url}}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
这不起作用,它显示来自Course 模型的数据,而不是来自课程和课程的数据
【问题讨论】:
-
lesson不是单个Lesson对象,它是allLessons 中的QuerySet,所以是“集合”。 -
好的,我必须编辑一下
-
你应该阅读Reverse relations。
-
到目前为止,您还没有接受许多问题的单一答案。他们不适合你吗?
-
我尝试了下面的答案,效果很好,我接受了答案
标签: django django-models django-views django-templates