Sorry I couldn't come with a more precise topic title and I must admit I'm still pretty new Django.
I am trying to work with Ajax and templates with splitted views but I can't achieve what I want, one way or another.
My goal is to be able to work with rendered templates and jquery hide/show instructions but I'm failing at some point.
Here is my urls.py:
from django.urls import path
from django.conf.urls import url
from . import views, inventory
urlpatterns = [
path('', views.index, name='index'),
url(r'^inventory', inventory.inventory, name='inventory'),
url(r'^buildInventory', inventory.buildInventory, name='buildInventory'),
]
My views index renders a templated "index.html" (there is a context that I removed for the illustration):
def index(request):
return render(request, 'myapp/index.html', context)
My index.html file :
{% extends "base.html" %}
{% load static %}
{% block delivery_form %}
<div id="mainblock">
....
</div>
{% endblock %}
And my base.html mostly contains my statics & headers:
{% load static %}
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="shortcut icon" type="image/png" href="http://web-iec/favicon.ico"/>
<link rel="stylesheet" type="text/css" href="{% static 'myapp/css/nice.css' %}">
<script type="text/javascript" src="{% static 'myapp/js/jquery.js' %}" ></script>
<script type="text/javascript" src="{% static 'myapp/js/jquery-ui.js' %}" ></script>
<script type="text/javascript" src="{% static 'myapp/js/inventory.js' %}" ></script>
<script type="text/javascript" src="{% static 'myapp/js/homepage.js' %}" ></script>
</head>
<body>
<div class="navBar">
<span class="navBtn" id="listDeplVer" title="Inventory">Inventory</span>
</div>
<div style="min-height: 100%;margin-bottom: -20px;">
{% block delivery_form %}
{% endblock %}
{% block inventory %}
{% endblock %}
</div>
</body>
</html>
Now what I'm trying to achieve, within my inventory.js I've got an onclick event that I'm trying to use to hide the home page content and replace it by the rendered html from my inventory.py view with associated html:
my inventory.py:
def inventory(request):
return render(request, 'myapp/inventory.html')
and my inventory.html:
{% extends "base.html" %}
{% load static %}
{% block inventory %}
<div id="inventoryblock">
// html
</div>
{% endblock %}
Finally my inventory.js is looking like:
$(document).ready(function () {
$( "#listDeplVer" ).click( function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/myapp/inventory',
beforeSend: function(){
$("#mainblock").fadeOut();
},
success : function(output){
$("#inventoryblock").html(output);
},
});
});
So like I said I was expecting that onclick my page's content is replaced by the rendered inventory page, but this is not working.
When using the web developper tools, if I open the XHR request for the inventory in a new tab it work just fine, so I assume I'm doing something the wrong way.
Before merging everything in one single file (js, views, html & so on) I wanted to ask if there is way to have something similar to work ?
Thank you for your help
Your source page doesn't have an "inventoryblock" div. That's only in the page you're loading via Ajax. So when your success function runs, it doesn't know where to put the output.
You need to put an empty div with id "inventoryblock" in your index.html.
Also, your inventory.html probably shouldn't inherit from anything. You don't need the full HTML file with the head block etc, you just want the fragment containing the contents of inventoryblock that you can insert into the requesting page. Remove everything other than the relevant HTML itself.
Related
I have created django template as:
{% extends '_base.html' %}
{% block title %}Checker{% endblock title %}
{% block content %}
<div class="container">
Click to open a pdf
</div>
{% endblock content %}
Whenever I try open that link Click to open a pdf it doesnot open that link.
I try this same process in plain html template it works as:
<!DOCTYPE html>
<html>
<head>
<title>Sample Code</title>
</head>
<body>
<h1>Opening a folder from HTML code</h1>
<a href="D:/Plagiarism Checker/plagiarismchecker/assignments/datasets/file161.pdf">Click to open a
folder</a>
</body>
</html>
I want to open that link from django template. But I cannot open that path. I will be very thankful if you can resolve this problem. Thank you!!!
You need to inform Django about the paths where you want it to look-up a file by adding the paths to STATICFILES_DIRS in settings.py.
Check out the documentation here
Once you have added say up to the plagiarismchecker folder in STATICFILES_DIRS, you can call the file from the template like this <a href="{% static 'assignments/datasets/file161.pdf' %}">
You paths need to be relative to the paths in STATICFILES_DIRS
I code with django and when I am working with django template, I do the below to avoid repeating code. Let me illustrate it with an example:
Suppose I have two pages in my website:
1) home
2) about
In django I code as below:
I first build a base.html :
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}home{% endblock title %}</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'css/my-base-css.css' %}">
{% block stylesheet %}{% endblock stylesheet %}
</head>
<body>
<h1>this is my site</h1>
{% block body %}{% endblock body %}
</body>
</html>
I then build home.html:
{% extends 'base.html' %}
{% block stylesheet %}<link rel="stylesheet" href="{% static 'css/home-page-css.css' %}">
{% endblock stylesheet %}
{% block body %}
<h2>This is home</h2>
{% endblock body %}
I also build about.html:
{% extends 'base.html' %}
{% block title %}
my-website-about
{% endblock title %}
{% block stylesheet %}<link rel="stylesheet" href="{% static 'css/about-page-css.css' %}">
{% endblock stylesheet %}
{% block body %}
<h2>This is about</h2>
{% endblock body %}
I now want to do the same without having a backend. I have a static website. How can I do the same without having a backend like django or php, etc.?
There is a similar question in here:
Include another HTML file in a HTML file
This can solve my problem. However, it is a little different from what I want. It is loading another html in an html file but I am looking for extending another html; I mean adding to another base.html and having a new html file
It looks like you're using the Django Templating Language which is similar to Jinja (I've only used this one because I've mostly used Flask but the way it works should be similar). Django uses this language in its template engine and the way it works is by basically taking your HTML file, passing it through a backend (Django), and replacing the variables/logic you have there with actual values. In the end, you'll have a fully built HTML file.
The short answer is no.
From my understanding of template engines, you need to have a backend that can actually work out which values (by replacing this syntax { some_variable }) you should put in the final HTML output.
When I am working outside Django file, everything works fine with javascript reading classes and Ids like
document.querySelector('.class_name').addEventListener
But when loaded in Django projects it gives an error that eventlistner can't read NULL.
{% comment %} css file for contacts.html {% endcomment %}
<script type="text/javascript" src="{% static 'info/js/for_recrs.js' %}"></script>
<link href="{% static 'info/css/for_recrs.css' %}" rel="stylesheet" type="text/css" />
{% endblock %}
Actually if you are declaring JS file in head, it will read it at that time itself without going through the HTML file. So, it reads null value of classes and ID.
To avoid that you can declare script file just beforeend of body.
OR
Use
window.onload = function() {
// do your stuff here.
}
It solved mine problem.
I need to fetch the the query string value from URL on the client side and that URL is passed from Django template. I am explaining my code below.
base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{% load static %}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<header>
<h1>Nuclear Reactor</h1>
{% if count > 0 %}
<b>Hi, {{ user.username }}</b>
Home
View Reactor status
logout
{% else %}
login / signup
{% endif %}
<hr>
</header>
<main>
{% block content %}
{% endblock %}
</main>
</body>
</html>
Here I am passing some query string value for home.html loading.
home.html:
{% extends 'base.html' %}
{% block content %}
<center><h1>Welcome</h1>
<p>This App allow to control the life cycle of the Nuclear Reactor and Retrive the status report </p>
<p>Status reportControl panel</p>
</center>
<script type="text/javascript">
window.onload=function(){
}
</script>
{% endblock %}
I need to fetch the query string using JavaScript when the home page rendered.
If you want to do this in the client side, I think you can use javascript location object:
<script type="text/javascript">
window.onload=function(){
querystring = location.search;
// do something
}
</script>
Otherwise, you can get the parameters from the request in the server side (in the view) and inject the object to the template.
I serialized an object of mine using the built in method with django and then passed it into my template. When I put {{goals}} in the html, the data shows perfectly. However, when I try to access it through a js script, it doesnt work. Why is this? I alerted it and it keeps coming as undefined.
#Python Views
def characterscreen(request):
goals = serializers.serialize("json", Goal.objects.filter(userprofile=userprof))
#goals = Goal.objects.filter(userprofile=userprof).values()
return render_to_response('levelup/characterscreen.html', {'goals': goals}, context_instance=RequestContext(request))
Python Model
class Goal(models.Model):
title = models.CharField(max_length = 30)
userprofile = models.ForeignKey(UserProfile)
type = models.CharField(max_length = 5)
def __unicode__(self):
return str(self.title)
JS File
$("body").onload = load_goals();
function load_goals (){
alert(goals);}
HTML
<!DOCTYPE html>
<html>
<head>
{% load staticfiles %}
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% static 'levelup/style.css' %}" />
{% block header %}{% endblock%}
</head>
<body>
<div id="headercontainer">
<div id="header">
</div>
</div>
{% block content %}{% endblock %} <script type="text/Javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script type="text/Javascript" src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">goals = "{{ goals|safe }}"</script>
<script type="text/Javascript" src="{% static 'levelup/script.js' %}"></script>
</body>
</html>
I tried removing the quotes and now the variable is just alerting a [object Object],[object Object] when I do alert(goals)
That's because external .js files aren't processed like html files are. This only works with inline scripts. So you should put this in your HTML file:
<script type="text/javascript">
goals = "{{ goals }}"
</script>
<script type="text/javascript" src="script.js" />
Then you can use the goal variable in script.js.
EDIT:
JSON always uses double quotes, so you'll have to put single quotes around it. Additionally, althrough a JSON string actually represents a real Javascript object when used without quotes, it's best to parse the JSON before you use it. As you seem to be using jQUery, use:
goals = $.parseJSON('{{ goals|safe }}')