Ajax search feature not working in django App - javascript

I'm following a tut from Mike hibbert and have tried to modify it a bit to suit my needs but it's not working. I wanted to use his way because my way was breaking the DRY rule, I had to write search logic for each of my views I thought it might be the order my js But I dont think it is. I could be wrong, as I am fairly new to prgramming. I'm not sure but i think the issue may be with my search being on the nav which I nav in an include. Heres my code
views.py
def search_title(request):
if request.method == "POST":
search_text = request.POST['search_text']
else:
search_text = ''
posts = Post.objects.filter(
Q(title__contains=search_text)|
Q(content__contains=search_text)
)
context = {
"posts": posts
}
return render(request, "posts/ajax_search.html", context)
my nav.html
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'posts:list' %}">HiSPANIC HEiGHTS</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<form method="POST" action=" " class="navbar-form navbar-right">
<div class="input-group">{% csrf_token %}
<input type="text" name="search" id="search" placeholder="search" value="{{ request.GET.q }}" class="form-control"
style="width: 350px">
<ul id="search-results">
</ul>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary"><span style="font-size:1.4em" class="glyphicon glyphicon-search"></span> </button>
</span>
</div>
</form>
<ul class="nav navbar-nav">
<li>Home</li>
<li>Sewp</li>
{% if user.is_authenticated %}
<li>Admin</li>
<li>Create</li>
{% endif %}
</ul>
</div><!--/.nav-collapse -->
</div>
base.html
{% load staticfiles %}
<html>
<head>
<title> {% block head_title %} try django 1.9 {% endblock head_title %}</title>
<link rel="stylesheet" href='{% static "css/base.css" %}'/>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
{% include "includes/nav.html" %}
{% include "includes/messages_display.html" %}
<div class="container">
{% if title == "posts" %}
<div class="jumbotron" style="margin-top: 80px">
{% block jumbotron %}{% endblock jumbotron %}
</div>
{% endif %}
{% block content %}{% endblock content %}
</div>
<!-- Latest compiled and minified JavaScript -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous">
</script>
<script src="{% static 'js/ajax.js' %}"></script>
<script src="{% static 'js/jquery.bootstrap-autohidingnavbar.js' %}"></script>
<script>
$("nav.navbar-fixed-top").autoHidingNavbar();
</script>
ajax.js
$(function(){
$('#search').keyup(function() {
$.ajax({
type: "POST",
url: "/posts/search/",
data: {
'search_text': $('#search').val(),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}
my posts/urls.py
urlpatterns = [
url(r'^$', post_list, name='list'),
url(r'^tag/(?P<slug>[\w-]+)/$', tag_list, name="tag_list"),
url(r'^create/$', post_create, name='create'),
url(r'^sewp$', sewp, name='sewp'),
url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'),
url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'),
url(r'^search/', search_title),
]
I see no errors in the network, I've switched back and forth from GET to POST, just trying to tweak things to make it work but nothing has changed. My jquery is from a CDN but I don't think that's an issue, but I am a newb and could be wrong. any help with this will be appreciated

Move your search url definition to the top of the urlpatterns list, so it doesn't get masked by the post_detail wildcards:
urlpatterns = [
url(r'^$', post_list, name='list'),
url(r'^search/', search_title),
url(r'^tag/(?P<slug>[\w-]+)/$', tag_list, name="tag_list"),
url(r'^create/$', post_create, name='create'),
url(r'^sewp$', sewp, name='sewp'),
url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'),
url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'),
]
From the docs:
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
And your post_detail regexp certainly matches search/.

I think you may be required to have $ at the end of your search url string.
url(r'^search/$', search_title),
This lets django know it's the end of the string. Unless you've confirmed that you've actually been able to dispatch to the search_title view.

Related

Error: Cannot read properties of null reading "checked"

I'm having trouble fully wiring on my Django applications submit button, it seems that the JS function does not understand which checked boxes to look for
all the console returns are "cannot read properties of null, reading "checked" I'm assuming its something with the function defining but I cannot seem to get it working
Heres the code:
<html>
<head>
{% load static%}
{% block content%}
<link rel="shortcut icon" type="image/png" href="{% static 'IMG/favicon.ico' %}"/>
<link rel="stylesheet" href="{% static 'CSS/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'CSS/jquery-ui.css' %}">
<script type="text/javascript" src="{% static 'JS/bootstrap.min.js' %}"></script>
<title>Task List</title>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="{% static 'JS/jquery-ui.min.js' %}"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
let _csrf = '{{csrf_token}}';
function submit_delete() {
var listItems = $("#list li input");
var checkedListItems = [];
listItems.each(function() {
if (document.getElementById(this.id).checked) {
checkedListItems.push(getTaskId(this.id));
console.log(checkedListItems);
}
})
$.ajax({
headers: { "X-CSRFToken": _csrf },
type: "POST",
url: "/ptm/item_delete",
data: {
'deleteList[]': checkedListItems
}
}).done(location.reload());
}
function getTaskId(str) {
return str.split('-')[1];
}
</script>
</head>
<body>
<div id="logo" class="border-success border border-3 rounded-2" style="width: 61.rem;">
<div class="card-body">
<img class="card-img" src="{% static '/IMG/Logo.png' %}">
</div>
</div>
<div id="taskList" class="card">
{% if task_list %}
<ul class="list-group" id="list">
{% for item in task_list %}
<li class="list-group-item" id='tdList'>
<input id="check-{{ item.id }}" type="checkbox" class="form-check-input me-1" value="">
<label class='d-flex w-100 justify-content-between'>
<h2 class="form-check-label" for="check-{{ item.id }}">{{ item.title }}</h2>
<small class='text-muted'>{{ item.date }}</small>
<input size='3'>
</label>
<h5 class="form-check-label">{{ item.description }}</h5>
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no current tasks assigned to this department.</p>
{% endif %}
</div>
{% csrf_token %}
<div id="taskEnter" class="card-footer">
<div class="d-grid mx-auto">
{% if task_list %}
<button type="button" onclick="submit_delete()" value='delete' class="btn btn-success btn-lg d-grid" value='delete'><i class="">Submit</i></button>
{% endif %}
</div>
</div>
</body>
{% endblock %}
</html>
In the part:
document.getElementById(this.id).checked
document.getElementById(this.id) evaluates to null, which doesn't have any properties, hence the exception you're getting. You're effectively doing null.checked which won't work.
It looks like you're trying to iterate over the checkboxes and determine whether they're checked or not. I'm reasonably confident that this inside the function you wrote will just refer to the window object, so calling this.id won't give you a checkbox id. You have actually already fetched all of the checkboxes (you're iterating over them!) so there's no need to refetch each one manually. Just do:
listItems.each(function(listItem) {
if (listItem.checked) {
checkedListItems.push(getTaskId(listItem.id));
console.log(checkedListItems);
}
})
Note that the function takes as argument the individual listItem (confusingly named since they're actually checkboxes but I'm following your nomenclature here) that each is currently iterating over. Which is what you need.
Try adding a child combinator ('>') to the element selector used in the first line of function submit_delete:
var listItems = $("#list li > input");
- or use a more precise selector of your own devisement.
As posted there appear to be descendant input elements of .list li of form <input size='3'> that don't have an id attribute. Processing these in each returns null from getElementById and throws the error that checked can't be a property of null.
About each
JAuery's each function fires its callback with a this value set to the element being processed during the iteration. The element is also provided to the callback as its second argument. Given elements in HTML should have unique id values:
For elements referred to by this that have id values, using this for the element is simpler than calling getElementById(this.id).
For elements (referred to by this) that do not have an id, !this.id) is a simpler conditional expression than getElementById(this.id)===null.
Filtering out elements that should not be mnatched during selection is preferable to filtering them out later.

I can't manage to import and use a javascript function from a .js into a django template. Ideas?

I have a javascript file project_dashboard.js with a few things defined inside of it and an html file where I try to call such function (amont other things).
For some reason, I keep getting the error that the function is not defined at HTMLButtonElement.onclick. What drives me crazy is that the first part of the .js is loaded and works (the css is changed if I click on table). So the script is there, but I can't use the function.
project_dashboard.js
$('table').on('click', 'tr.parent .fa-chevron-down', function(){
$(this).closest('tbody').toggleClass('open');
});
function EnablePositionEdit(position_id) {
const checked_events = []
$("#edit_button_____" + position_id).toggle()
$("#save_button_____" + position_id).toggle()
$("#delete_____" + position_id).toggle()
inputs = document.querySelectorAll(".availability_____" + position_id + " input")
inputs.forEach(input => {
input.removeAttribute("disabled")
})
}
html
{% extends 'action/base.html' %}
{% block extrastylesheets %}
{% endblock extrastylesheets %}
{% block content %}
<head>
{% load static %}
<link rel="stylesheet" href="{% static 'action/css/project_dashboard.css' %}">
<link href="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
...
<div id="edit_button_____{{ position.id }}" style="display: block;">
<button class="btn" style="font-size:10px; color: rgb(59, 89, 152);" onclick = EnablePositionEdit('{{ position.id }}')> <i class="fa fa-pencil"></i> </button>
</div>
...
{% endblock content %}
{% block extrascripts %}
<script src="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.js"></script>
<script type="text/javascript" src="{% static 'action/js/project_dashboard.js' %}"></script>
<script>
$(document).ready(function() {
$('.summernotable').summernote({
toolbar: [],
});
});
....
</script>
{% endblock extrascripts %}
You have to wrap the function name in quotes, as you do for all attributes, and place the script that contains the function before you call the function.
<script type="text/javascript" src="{% static 'action/js/project_dashboard.js' %}"></script>
<button class="btn" style="font-size:10px; color: rgb(59, 89, 152);" onclick = "EnablePositionEdit('{{ position.id }}')"> <i class="fa fa-pencil"></i> </button>

How do I handle CSRF for Google Sign-In? (Using Python and Django)

I'm building a simple Login page using Python and Django. I want to give the users the choice to login using either the Django account or Google Sign-In.
I've build some simple HTML and functions to flow between 4 pages: Main, login_success,logout_success and already_logged_in
As far as I've understand, I've set up at the very least a button on my login page, with some relevant scripts.
So, then I deploy to my Google Cloud, access the site, see the button and click on it and it redirects me to a Google Sign-In page where I can choose my account. I click on the account and I get a Forbidden: CSRF Error.
Am I missing something?
I am not sure how to debug this.
This is my Main login HTML.(I'm not sure if the rest are needed to be shown?)
{% load i18n %}
{% block content %}
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<head>
<title>Google Signin Testing</title>
<style>
.left {
float: left;
width: 40%;
padding-left:32%;
padding-top:13%;
height: 75%
}
.right {
float: left;
width: 40%;
padding-top:5%;
height: 100%
}
h1 {
text-shadow: 2px 2px 2px #aaa;
}
h2.maintitle {
padding-left:5%;
font-variant: small-caps;
font-size: 36px;'
}
</style>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<script>
function onSignIn(credentialResponse) {
document.body.innerHTML = "Signed in";
}
</script>
</head>
<body>
<div class='row' >
<div class='container-fluid col-6 left' >
</div>
<div class='container-fluid col-6 right' >
<h1>{% trans 'Log-In' %}</h1>
{% if request.user.is_authenticated %}
<p>{% trans 'You are already logged in' %}, my homepage</p>
{% else %}
<form action="" method="post">
{% csrf_token %}
{% if form.non_field_errors %}
{% for x in form.non_field_errors %}
<text style="color:red; font-size:12px;" id='{{field.label}}'><b>{{x}}</b></text>
<p/>
{% endfor %}
{% endif %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.label_tag }} {{ field }}
<br/>
{% for x in field.errors %}
<text style="color:red; font-size:12px;" id='{{field.label}}'><b>{{x}}</b></text>
{% endfor %}
<p/>
</div>
{% endfor %}
<input style='max-height:8vh;font-size:clamp(5px, 2.3vh, 30px);object-fit;' type="submit" value="Log In"></input>
<br/><br/>
<!---div id="g_id_onload"
data-client_id="[Google Cloud ID]"
data-context="signin"
data-ux_mode="popup" /* popup */
data-login_uri="[Google Cloud URL]"
data-auto_prompt="false">
</div--->
<div id="g_id_onload"
data-client_id="[Google Cloud ID]"
data-context="signin"
data-ux_mode="redirect"
data-login_uri="[Google Cloud URL]"
data-auto_prompt="false">
</div>
<div class="g_id_signin"
data-type="standard"
data-shape="rectangular"
data-theme="filled_blue"
data-text="signin_with"
data-size="medium"
data-logo_alignment="left"
data-width=300 >
</div>
</form>
<br/><br/><p>{% trans 'Forgotten your password?' %}</p>
{% endif %}
</div>
</div>
</body>
<!--Redirection if already Logged-In in cookies -->
{% if request.user.is_authenticated %}
<script type="text/javascript">
var csrftoken = Cookies.get('csrftoken'); //using js.cookie.js
window.location = "{% url 'login_success' %}";
</script>
{% endif %}
</html>
{% endblock %}
Im using a Django form to override the default auth_views.LoginView which returns to this HTML.
Edit
I came across a part of Google's documentation that addresses this here, and the more I read it, I came to realise that their sample code might not be Javascript, but Python, so I inserted the entire sample into my source code.
Thing is....they're using webapp2, which I check is only compatible with Python 2, NOT Python 3, which is what Im using. So that's back to the drawing board.

Uncaught Syntax Error: Unexpected identifier game.js:25

I'm making my first flask app which is a text adventure and a separate section to leave a review. I'm trying to follow along with a text adventure tutorial. I've got my site running however when I refresh the page to see my progress the changes in game.js are not reflected and I'm met with the error in the title.
This is my first post on Stack Overflow so I've put all of my code below. Thanks in advance for any help! I'm still relatively new so sorry for any stupid mistakes, Paddy.
game.js
const textElement = document.getElementById('text')
const optionsButtonsElement = document.getElementById('options-buttons')
let state = {}
function startGame() {
state = {}
showTextNode(1)
}
function showTextNode(textNodeIndex) {
const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
textElement.innerText = textNode.text
while (optionsButtonsElement.firstChild)
optionsButtonsElement.removeChild(optionsButtonsElement.firstChild)
}
function selectOption(option) {
}
const textNodes = [
{
id:1
text: 'You wake up staring at the ceiling of your bunker.',
options [
{
text: 'Turn on the radio',
nextText: 2
},
{
text: 'Grab your pistol and pack up the remainder of your supplies.',
}
]
}
]
startGame()
game.html
{% block title %}Get ready to play!{% endblock %}
{% block content %}
<body>
<div class="container">
<div id="text">Text</div> <br/>
<div id="option-buttons" class="btn-grid">
<button type="button" class="btn btn-outline-dark btn-lg btn-block">Option 1</button>
<button type="button" class="btn btn-outline-dark btn-lg btn-block">Option 2</button>
<button type="button" class="btn btn-outline-dark btn-lg btn-block">Option 3</button>
<button type="button" class="btn btn-outline-dark btn-lg btn-block">Option 4</button>
<script src="{{ url_for('static', filename='js/game.js')}}"></script>
</div>
</body>
{% endblock %}
app.py
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
#Initialising the database
db = SQLAlchemy(app)
#Creating a database model
class Posts(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
#Creating a function to return a string when a post is added to db
def __repr__(self):
return '<Content %r>' % self.id
#app.route('/')
def index():
return render_template("index.html")
#app.route('/game')
def game():
return render_template("game.html")
#app.route('/blog', methods=['POST', 'GET'])
def blog():
if request.method == "POST":
post_content = request.form['content']
new_post = Posts(content=post_content)
try: #Push the blog post to the db
db.session.add(new_post)
db.session.commit()
return redirect('/blog')
except:
return "There was an error adding your post"
else:
posts = Posts.query.order_by(Posts.date_created)
return render_template("blog.html", posts=posts)
#app.route('/update/<int:id>' , methods=['POST', 'GET'])
def update(id):
post_to_update = Posts.query.get_or_404(id)
if request.method == "POST":
post_to_update.content = request.form['content']
try:
db.session.commit()
return redirect('/blog')
except:
return "There was a problem updating your blog post"
else:
return render_template('update.html', post_to_update=post_to_update)
#app.route('/delete/<int:id>')
def delete(id):
post_to_delete = Posts.query.get_or_404(id)
try:
db.session.delete(post_to_delete)
db.session.commit()
return redirect('/blog')
except:
return "There was a problem deleting this post :("
my base.html template
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<title>
{% block title %}GEN TITLE{% endblock %}
</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{{ url_for('index')}}">Patricks Site</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="{{ url_for('index')}}">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('game')}}">Game</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('blog')}}">Blog</a>
</li>
</ul>
</div>
</nav>
</br>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<!-- Option 2: jQuery, Popper.js, and Bootstrap JS
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
-->
{% block content %}
{% endblock %}
</body>
</html>
Sorry for the wall of text, I wasn't quite sure how much I should show. Thanks
Your error is telling you to look at line 25 of game.js.
It appears you're missing a colon on that line, after options, and a comma after id: 1. You have:
const textNodes = [
{
id:1
text: 'You wake up staring at the ceiling of your bunker.',
options [...],
You need:
const textNodes = [
{
id:1,
text: 'You wake up staring at the ceiling of your bunker.',
options: [...],

Django - document.querySelector finds the base.html tags only

I have the django app with traditional base.html approach, which is extended in every other template. However, I have a problem with reaching out html tags which are outside the base.html template.
var myHeading = document.querySelector(".contentfont");
console.log(myHeading);
gives me:
<div class="contentfont">
<!-- JS -->
<script src="/static/js/squad_picker.js" type="text/javascript"></script>
<h1 id="test" class="heading test"> test page </h1>
<div class="container">
<div class="jumbotron">
</div>
</div>
</div>
but when I try for example
var myHeading = document.querySelector(".contentfont > h1");
it always gives me null. The same happens while trying to access anything which is not inside base.html directly by id or class.
I add the part of base.html:
<div class="contentfont">
{% block content %}
{% endblock %}
</div>
and the html which is extending it:
{% extends 'my_app/base.html' %}
{% load static %}
{% block content %}
<!-- JS -->
<script src="{% static 'js/squad_picker.js' %}" type="text/javascript"></script>
<h1 id='test' class="heading test">test page </h1>
<div class="container">
<div class="jumbotron">
</div>
</div>
{% endblock %}
SOLVED: tag should be at the end of the html file...

Categories

Resources