[Answered ]-How to show messages using DetailView on Django

1👍

In the template, you can render this as:

{% for message in object.message_set.all %}
    {{ message.body }}
{% endfor %}

This will thus, for the Post object in the context named object retrieve all the related Messages.

If you want to fetch the data of the related user as well, you can work with a Prefetch object [Django-doc]:

from django.db.models import Prefetch

class PostDetailView(DetailView):
    model = Post
    queryset = Post.objects.prefetch_related(
        Prefetch('message_set', Message.objects.select_related('user'))
    )

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: Django’s DateTimeField [Django-doc]
has a auto_now_add=… parameter [Django-doc]
to work with timestamps. This will automatically assign the current datetime
when creating the object, and mark it as non-editable (editable=False), such
that it does not appear in ModelForms by default.

Leave a comment