Related to Django

Template issue

  • Regarding URL and template tags

    • create templates for individual apps
    • folder structure

      <app-dir>
          |-> templates
              |-> <dir-with-same-name-of-app>
                  |-> file1.html
                  |-> file2.html
      
    • this may cause some issues if html paths aren't defines properly

    • assuming file1.html is base.html and file2.html is home.html, and home extends base, the extend tag should look like this

      {%extends '<appname>/base.html>'%}
      

      NOT

      {%extends 'base.html>'%}
      
    • if urls.py is setup properly, django will definitely find the templates directory but wont be able to load home.html or base.html as they are inside templates/<appname> directory.

  • Regarding Views

    • assuming using ClassViews, the template_name should look like this
      template_name = '<appname>/home.html'
      

Sending Context Data while using TemplateView

  • reference Ref 1 Ref 2

  • lets assume a template view

    from django.views.generic.base import TemplateView
    from .service import get_json_data
    
    class HomePageView(TemplateView):
        template_name = 'someapp/home.html'
    
        def get_context_data(self, *args, **kwargs):
            context =  super().get_context_data(*args, **kwargs)
            context['data'] = get_json_data()
            return context
    
  • get_json_data is a very simple function that uses requests module to consume an API and return the json output

  • this view receives the json data from get_json_data() and stores as an item of the context, when called, it sends the context with it, and allows html pages to show the data
  • in home.html using this code bellow will excerpt the json data received from api
    <p>{{ data }}</p>
    

Quick Access

Faster way to traverse the blog