Aliquis
Aliquis

Reputation: 2319

Django: How structure/use project with multiple apps

I've already read the official Django tutorial and many other questions here on stackoverflow.com, but it seems like there is no real answer to my question or I just don't get it. Unfortunately, I could not find an appropriate tutorial with more than one app.

My problem: A Django project usually consists of multiple apps. What I don't get is how those apps can work together.

Example: Let's say we build a news website and this news website has blog posts, polls and a comments area etc. So I think it would make sense to create an app called polls, another app called blog and the app comments.

So, when you browse to url.com/news/5 for example, you'll see the blog post with the id 5. Or when you browse to url.com/polls/2 you'll see the poll with the id 2. Everything ok.

Now, however, I don't want it to be separated. What I don't get is when I want to have those parts of a website on a single webpage (like in most of the websites). That means if I browse to url.com/news/5 it should not only display the news but also the poll (because the poll belongs to this news page thematically) and at the bottom of the page the comments to that article.

How do I structure it and "glue" it together?

Normally, when I browse to url.com/news/5 the defined view function within the blog app is run and provides the HttpResponse. With this solution, however, I cannot have the poll and comments at the same page. I hope it's clear to you what my problem is.

What is "best practice" to display different apps on a single webpage? Or is it done completely different?

I am also very happy if you can give me a link to a real-world example or nice tutorial that covers this issue.

Upvotes: 0

Views: 1519

Answers (1)

Tony
Tony

Reputation: 2482

Using Class-based generic views and providing extra context. Here is a link from the documentation:

https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-display/#adding-extra-context

and here is the example code:

from django.views.generic import DetailView
from books.models import Publisher, Book
class PublisherDetail(DetailView):

    model = Publisher

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PublisherDetail, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['book_list'] = Book.objects.all()
        return context

As you can see the main model is Publisher and with get_context_data you can add another context: context['book_list'] = Book.objects.all() that retrieves also all books from the database. You can combine multiple models with this.

Upvotes: 1

Related Questions