Hello!
I have two app in my project where I want to render the the query from a certain view from app 1 to another template inside app 2. I hope it makes sense.
I’ve done some research and one way is to render the query from app 1 in a template in app 1 and then include it, using {% include “template path” %}, inside a template in app 2 where it is supposed to be displayed.
My question is, is this really the correct way?
I tried this technique for a random text and it was displayed in my template in app 2. However, the actual view function is not rendered.
Is there something wrong in the logic?
I have made sure that there are instances of User, Room and Comment in the database so the bug must raise from the view function, I believe.
View:
def room_comments(request, room_id):
room = get_object_or_404(Room, id=room_id)
comments = Comment.objects.filter(room=room).order_by("-date")
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.room = room
comment.member = request.user
comment.save()
return HttpResponseRedirect(reverse("main_app:roomdetail", args=[room_id]))
else:
form = CommentForm()
context = {"comments": comments, "form": form, "room": room}
return render(request, "main_app/roomspage_roomdetail.html", context)
URL
from django.urls import path, include
from . import views
app_name = "messages_app"
urlpatterns = [
path("<int:room_id>/", views.room_comments, name="room_comments"),
]
Model:
class Comment(models.Model):
room = models.ForeignKey(
Room, on_delete=models.CASCADE)
member = models.ForeignKey(
Member, on_delete=models.CASCADE, null=True)
body = models.TextField(max_length=150, blank=False)
comment_date = models.DateTimeField(auto_created=True)
def __str__(self):
return str(self.body[0:20])
Template in app 1:
{% block content %}
{% for comment in comments %}
{{comment.body}}
{% endfor %}
<form action="#" method = "POST">
{% csrf_token %}
{{form}}
</form>
{% endblock content %}
I appreciate all tips!