在同一页面显示两个模特Django

xienkqul  于 2023-02-05  发布在  Go
关注(0)|答案(1)|浏览(119)

我有两个模型:

class Post(models.Model):
title= models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
postimage = models.ImageField(null= True, blank= True, upload_to="images/")
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title + " | "+ str(self.author)
def get_absolute_url(self):
    return reverse('article_deatil', args=(str(self.id)))

class AboutMe(models.Model):
title1= models.CharField(max_length=255, default="About Me")
body = models.TextField()
skill1= models.CharField(max_length=255)
skill1body = models.TextField()
skill2= models.CharField(max_length=255)
skill2body = models.TextField()
skill3= models.CharField(max_length=255)
skill3body = models.TextField()
edu1=models.CharField(max_length=255)
edu1body =  models.TextField()
edu2=models.CharField(max_length=255)
edu2body =  models.TextField()
edu3=models.CharField(max_length=255)
edu3body = models.TextField()

def __str__(self):
    return self.title1

我想在我的home.html中显示这两个文件

class HomeView(ListView):
model = Post
template_name = 'home.html'
queryset = Post.objects.order_by('-published_date')[:3]

url.py

urlpatterns = [
path('',HomeView.as_view(), name="home"),
path('',PostViewList.as_view(), name="postlist"),

]
我是django新手,不知道如何在一个模板中显示case两个模型,我确实在html中添加了post.body和其他标签,但是没有显示关于我的部分。

cwtwac6a

cwtwac6a1#

假设您需要多一个AboutMe模型的查询集(如Post模型)。
您只需按以下方式使用get_context_data()

class HomeView(ListView):
    model = Post
    template_name = 'home.html'
    queryset = Post.objects.order_by('-published_date')[:3]

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['about_me_records'] = AboutMe.objects.all()
        return context

现在,您还有一个查询集about_me_records要在模板中使用并迭代。

相关问题