View from multiple apps

Hi everybody.

This is my first message. I’m using Django for a few times, and I really enjoy it (it’s really awesome and easy to develop projects). I just have one question, regarding splitting the project in different apps.

I have a project X, and several features (like a blog, pictures, some datas collected via an API, etc). For me, it’s obvious to split them into several apps (a blog app, a data app, a gallery app, etc…).

My question is: how make a homepage, with different apps? On this homepage, I want to show several informations, from different apps, like the last 3 blog posts, the last 3 pictures, etc, on the same template.

So :

  • is it possible to do such a thing correctly et properly? And how to?
  • or should I put those features in a same and single app? It’s more easier to me, but is it the proper way?

I didn’t find some examples in documentation.

Regards,

N.

1 Like

Yes, there are multiple ways to do this.

One option you have is to create your template with the different areas on the page for data from each app, then have your home page call functions from each app to return the data to be displayed. You can then pass that data into your template to be rendered.

In very rough terms then, your home page view could look something like this:

def home_page_view(request):
    last_3_blogs = blog_app.get_last_3_posts()
    last_3_images = image_gallery_app.get_last_3_images()
    highest_ranked_movies = movie_ranking_app.get_top_3()
    context = {'blog_posts': last_3_blogs, 'images': last_3_images, 'movies': highest_ranked_movies}
    return render(request, 'home/page.html', context)

(There’s quite a bit more to this than that, but it’s the skeleton of the idea.)

Ken

2 Likes

Thanks a lot KenWhitesell, I got the idea, and it helped me!

Regards,

N.

now, can I do an API of that? I mean, I won’t be doing the template, so I want to send that data in an api format, is it possible?

Welcome @jiggy-the-father !

Absolutely.

Functionally and structurally, there’s no difference in the fundamental operation of a “standard” Django view and an “API” view. The only difference is how the data is returned.

A standard Django view is going to return HTML. An API view isn’t going to render a template, it’s going to serialize the data and return that data as the response.

1 Like

thank you, Mr. Ken.

I had to search a little bit more, but I achieved the goal. thank you for your suggestion.