Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to integrate an app inside another app

i would like to know how can we "call" an application from inside a different application. Basically, i have, for example :

  • a Calendar app that does a certain process to render a calendar in html
  • a "Main" app that shows the index.html of a website

I would like the Main app to invoke the Calendar app and insert what it renders in the sidebar.

The CodeIgniter framework for example, can handle that. A controller can invoke another controller, saves what it returns (the html output) in a variable, and finally includes this variable in the context that will be used to render the final html file.

Is that possible with Django ? Thanks

like image 982
Firas Avatar asked Oct 04 '22 08:10

Firas


1 Answers

Well, i think i may found a solution. I'm new to Django so i don't know if it's a good way to do it, if it brokes some conventional rules, if it open some security hole, or if simply, there are other better methods, but anyway, it works ...

So, i created my application Calendar, and my application Show. I want Show to invoke Calendar, render its template, and then insert the result inside a template of Show.

To do that i used TemplateResponse instead of HttpResponse on the Calendar side :

# Calendar view

from django.template.response import TemplateResponse

def render_calendar(request):
    return TemplateResponse(request, 'calendar/calendar-template.html', {})

Then on the Show side, get the TemplateResponse instance, invoke its render() method, and finally insert the rendered_content inside the context :

# Show view

from calendar import views

def show(request, show_id):
    cal = views.render_calendar(request)
    cal.render()
    context = {"calendar": cal.rendered_content}
    return render_to_response("show/show-template.html", context)

And that does the trick !

like image 164
Firas Avatar answered Oct 11 '22 04:10

Firas