Django and Template

Asked

Viewed 772 times

7

Good night! Guys, I’ve been in trouble for four days and unfortunately I haven’t been able to fix it yet! I’m working with tamplates in Django, but I’m having problems, because nothing appears in the pages!

This is the basic structure of the base.html

    <!DOCTYPE html>

    {% load staticfiles %}

    <html lang="en">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

        <title>{% block title %}{% endblock %}</title>
        {% block head_override %}{% endblock head_override %}


    </head>

    <body{% block body_override %}{% endblock body_override %}>


                        {% block content %}


                        {% endblock content %}

{% block extra_javascript %}


{% endblock extra_javascript %}

</body>

</html>

Here is the html page that extends "base.html". There is more information on the page, but I really want to show you is Djando’s Structure, as I believe the error is related to this! Because I did the test without using Djando Templates and it worked :(!!

{% extends "base.html" %}
{% load staticfiles %}
{% block title %}Google Maps{% endblock %}

{% block head_override %}

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />



{% endblock head_override %}


{% block content %}

    <div class="row">
    <div class="col-md-6">
        <div onload=" initialize()" class="main-box clearfix">
            <header class="main-box-header clearfix">
                <h2>MAPA COM PONTEIROS</h2>
            </header>

            <div class="main-box-body clearfix">
                <div id="map" class="map-content"></div>
            </div>
        </div>
    </div>
    </div>



{% endblock content %}


{% block extra_javascript %}

    <script type="text/javascript">
        function initialize() {
            var mapOptions = {
                center: new google.maps.LatLng(-34.397, 150.644),
                zoom: 8
            };
            var map = new google.maps.Map(document.getElementById("map-canvas"),
                    mapOptions);
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>

{% endblock extra_javascript %}

This is the View

__author__ = 'Sara Fernandes'

from django.shortcuts import render_to_response, render
from django.template import RequestContext, loader
from django.shortcuts import redirect # Funcao para executar um http-redirect

#from django.http import HttpResponseRedirect # Funcao para redirecionar o usuario
#Criar as Views aqui

# pagina inicial do projeto dweb

def homepage(request):
    return render_to_response('indexTEMPLATE.html',
        context_instance= RequestContext(request))


def googlemaps(request):
     return render(request, "maps.html") # redireciona o usuario para a p�gina de login

def redirecionalogin(request):
     return render(request, "login.html") # redireciona o usuario para a p�gina de login

py Settings.

  """
Django settings for web project.

Generated by 'django-admin startproject' using Django 1.8.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True


ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'web',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'web.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]



WSGI_APPLICATION = 'web.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'NAME': 'gerenciador.db',
        'USER':'', 'PASSWORD': '',
        'PORT':'', 'PORT': '',


    }
}


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'web/templates'),
)
  • what its directory structure?

  • Just a tip @sara-Fernandes, never reveal your SECRET_KEY

2 answers

5

Your templates directory has to be inside your app web and its Settings.py and the variable TEMPLATES in the key DIRS has to have that the path of that directory.

TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [
                os.path.join(BASE_DIR, 'web', 'templates')
             ],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

1

Sara, you don’t need to override, apparently it’s all right, only inside your Settings.py, delete the template_dirs line:

TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'web/templates'),
)

why? well, as your template folder is inside your web app, it by default and automatically recognized, inside your base.html template remove the {% block body_override %}{% endblock body_override %}, and the {% block extra_javascript %} try to work normally with js, block content will take everything inside the body of your html, try using js inside the block content so:

{% block content %}

<div class="row">
<div class="col-md-6">
    <div onload=" initialize()" class="main-box clearfix">
        <header class="main-box-header clearfix">
            <h2>MAPA COM PONTEIROS</h2>
        </header>

        <div class="main-box-body clearfix">
            <div id="map" class="map-content"></div>
        </div>
    </div>
</div>
</div>

<script type="text/javascript">
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(-34.397, 150.644),
            zoom: 8
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"),
                mapOptions);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>


{% endblock content %}

if these modifications don’t work, put your project on github and post the link here that I will try to help you with it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.