Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Showing two model in same page Django

I have two models:

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 

I want to show both of them in my home.html

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

url.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

]

I’m new to django and not sure how to show case two model in one template. I did put the post.body and other tags in my html but it not showing the About me part.

>Solution :

Assuming that you want one more queryset of AboutMe model like Post model.

You should simply use get_context_data() in the following way:

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

Now, you have one more queryset about_me_records to use in the template and iterate over.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading