When I open the file angular.html the angularjs with Chrome, the html work normally, showing the array of information in the table. However, when I use Django, the same angular.html file, angularjs does not show the array of information in the table. I do not know what can I do?
File angular.html
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<script>
function tabela($scope){
$scope.linhas2=[["Nexus S1","Oi1"],["Nexus S2","Oi2"],["Nexus S3","Oi3"]]
}
</script>
</head>
<body>
<div ng-controller="tabela">
<table>
<tr ng-model="item2" ng-repeat="item2 in linhas2">
<td ng-repeat="item3 in item2">{{ item3 }}</td>
</tr>
</table>
</div>
</body>
</html>
File views.py
from django.shortcuts import render_to_response
def ang(request):
return render_to_response("angular.html")
File urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^angular/','bvmfconsulta.views.ang'),
)
The Django finds angular.html but shows a blank page.
The problem is that both Django and AngularJS share the same syntax for variable substitution in templates.
The easiest option would be to tell Django not to use it's syntax in places you need to use angularjs variable substitution - in other words, use verbatim tag:
{% verbatim %}
<div ng-controller="tabela">
<table>
<tr ng-model="item2" ng-repeat="item2 in linhas2">
<td ng-repeat="item3 in item2">{{ item3 }}</td>
</tr>
</table>
</div>
{% endverbatim %}
See other options at:
Integrate AngularJS with Django
Indeed, you can use the {% verbatim %} tag. There is another way: you can change the AngularJS tags:
var app = angular.module('dashboardApp').config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
});
Your code will transform to:
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<script>
function tabela($scope){
$scope.linhas2=[["Nexus S1","Oi1"],["Nexus S2","Oi2"],["Nexus S3","Oi3"]]
}
</script>
</head>
<body>
<div ng-controller="tabela">
<table>
<tr ng-model="item2" ng-repeat="item2 in linhas2">
<td ng-repeat="item3 in item2">{$ item3 $}</td>
</tr>
</table>
</div>
</body>
</html>
This way you can visually distinguish between Angular and Django Template tags. Cheers!
Related
I have an angular.js app where the index.html looks something like with ng-app in the <html> tag
<html lang="en" ng-app="app">
<head></head>
<body>
<custom-navbar-directive></custom-navbar-directive> //angular js directive
<custom-loader></custom-loader>
<!-- To render components -->
<div ui-view ng-cloak></div>
</body>
</html>
I was following the steps in the single-spa angular.js guide. I removed the ng-app from <html> tag and added the following in my app.js
System.register([], function (_export) {
return {
execute: function () {
_export(
window.singleSpaAngularjs.default({
angular: angular,
mainAngularModule: "app",
uiRouter: true,
preserveGlobal: false,
})
);
},
};
});
Also I did the import map and singleSpa.registerApplication steps in the index.html
My issue is now the content is rendering but the <custom-navbar-directive> and <custom-loader> are missing. I added them inside the index.html since they are commonly used in each html template.
When I inspect and checked the rendered html I noticed that they are outside the loaded single spa angularjs app
<custom-navbar-directive></custom-navbar-directive>
<custom-loader></custom-loader>
<div id="single-spa-application:legacyAngularApp">
<div id="__single_spa_angular_1" class="ng-scope">
<!-- content -->
</div>
</div>
I guess since they are directives if those are inside the <div id="__single_spa_angular_1" class="ng-scope"> then it should render.
Any idea how to solve this?
I created an environment using pycharm & installed adminlte by git clone from https://github.com/app-generator/django-dashboard-adminlte.git. And installed adminlte3 , django3.1 & all requirements. Then run python manage.py runserver and registered a new user & was able to login ,view all pages, added new link to a html page. But I am unable to add view with jsonresponse to a button click on new page, geting Error 500 - Server Error.
My new html page is
{% extends "layouts/base.html" %}
{% block title %} Layout Boxed {% endblock %}
<!-- Element injected in the BODY element -->
{% block body_class %} sidebar-mini layout-boxed {% endblock body_class %}
<!-- Specific Page CSS goes HERE -->
{% block stylesheets %}
<!-- Google Font: Source Sans Pro -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Font Awesome -->
<link rel="stylesheet" href="/static/assets/plugins/fontawesome-free/css/all.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="/static/assets/css/adminlte.min.css">
<link rel="stylesheet" href="/static/assets/css/mapstyle.css">
<link rel="stylesheet" href="/static/assets/js/pages/gis/dist/map.css">
<style>
.map {
margin: 0;
padding: 0;
width: 900px;
height: 500px;
background:white !important;
border:1px solid #ccc;
}
</style>
{% endblock stylesheets %}
{% block content %}
<div class="content-wrapper">
<div id="lyrDiv"></div>
<div id="map" class="map"></div>
<button id="search">Search</button>
</div>
{% endblock content %}
<!-- Specific Page JS goes HERE -->
{% block javascripts %}
<!-- jQuery -->
<script src="/static/assets/plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="/static/assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="/static/assets/js/adminlte.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="/static/assets/js/demo.js"></script>
<script src="/static/assets/js/pages/map.js"></script>
<script src="/static/assets/js/pages/search.js"></script>
{% endblock javascripts %}
search.js
$( "#search" ).click(function() {
$.get('/search/',{'csrfmiddlewaretoken':csrftoken},function(data){
alert(data); // here getting Error 500 - Server Error
});
});
I added below line to /django-dashboard-adminlte/app/urls.py
re_path(r'^search/$', search.spatial_srch, name='search'),
and search.py
from app.models import *
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
#csrf_exempt
def spatial_srch(request):
data= Demotable.objects.all()
searchArr = []
output = {}
for c in data:
searchArr.append({'type': 'Feature', 'properties': {'id':c.id,'name': str(c.name)},'geometry': {'type': 'Point', 'coordinates': [c.the_geom.x, c.the_geom.y]}})
output = {'type': 'FeatureCollection', 'features': searchArr}
return JsonResponse(output)
When I click on the 'Serach' button the request is not going to the view search.py What is wrong in my code ? what configuration did I miss?
The post shows
The Error 500 shows only adminlte Error page. Nothing more
The problem is in the (not so nice) way they generate the error. It's anti-pattern hell there, but in short it means there's an except thrown in either:
finding the template
loading the template
or rendering the template
and they catch it and don't let you see what happened. Not very nice code and you're have to modify that file to even begin debugging it:
#login_required(login_url="/login/")
def pages(request):
context = {}
# All resource paths end in .html.
# Pick out the html file name from the url. And load that template.
try:
load_template = request.path.split('/')[-1]
html_template = loader.get_template( load_template )
return HttpResponse(html_template.render(context, request))
except template.TemplateDoesNotExist:
html_template = loader.get_template( 'page-404.html' )
return HttpResponse(html_template.render(context, request))
# Remove or comment these lines:
#except:
#
# html_template = loader.get_template( 'page-500.html' )
# return HttpResponse(html_template.render(context, request))
Also I'm not sure this the specific spot where the error is generated, they might be doing similar things in other places.
Edit
This is very .... unprofessional code:
# Matches any html file
re_path(r'^.*\.*', views.pages, name='pages'),
No, it doesn't not match any "html" file - it matches everything cause they don't get regular expressions:
^ - start of string
.* - anything or nothing
\.* - >>>zero<<< or more dots
Result: \.* is ignored as it is irrelevant so it matches everything and if you placed your re_path below it, it will never be consulted, because Django uses first match wins approach.
So your url matches theirs, which then routes it to pages view:
load_template = request.path.split('/')[-1]
Since request.path is '/search/', '/search/'.split('/')[-1] gives the empty string and that creates your problem.
I highly suggest fixing their url path:
# Matches any html file
re_path(r'\.html$', views.pages, name='pages'),
Or put your re_path above theirs.
This question already has answers here:
How to escape {{ or }} in django template?
(10 answers)
Closed 3 years ago.
I am unable to use double braces to resolve variables. Here's my js code.
var app = angular.module('toDo',[]);
app.controller('toDoController', function($scope, $http) {
$http.get('/todo/api/').then(function(response) {
$scope.todoList = response.data;
});
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>To Do List</title>
{% load static %}
<link rel="stylesheet" href="{% static 'css/todo.css' %}">
</head>
<body ng-app="toDo" ng-controller="toDoController">
<h1>Todo List</h1>
<form ng-submit="add()">
<input type="text" ng-model="todoInput" placeholder="Add a new todo task...">
<button type="submit">Add Task</button>
</form>
<br>
<div ng-repeat="todo in todoList">
<input type="checkbox" ng-model="todo.done"><a ng-href="/todo/api/{{todo.id}}" ng-bind="todo.task"></a>
</div>
<p>
<button class="delete" ng-click="delete()">Delete</button>
<button class="update" ng-click="update()">Update</button>
</p>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.js"></script>
<script src="{% static 'js/todo.js' %}"></script>
</body>
</html>
tasks which displayed in screen should redirect me to the url "/todo/api/". But values given in the braces not resolving it's ID. Currently the hyperlink redirecting always to the url "/todo/api/".
Kindly let me know if I am doing anything wrong or help me to fix this issue.
The brackets are interpreted by the Django template renderer. You can use {% verbatim %}…{% endverbatim %} [Django-doc] to avoid interpreting the double curly brackets, like:
<a {% verbatim %}ng-href="/todo/api/{{todo.id}}"{% endverbatim %} ng-bind="todo.task"></a>
I have a question. I need to add HTML boiler plate and additional data to a html file.
I have a script that takes in a CSV file, processes it(clean, sort, etc) and use pandas .to_html. Problem is it gives me only table tags and the contnet inside.
Content is something like this:
<table border="0" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>AK ID</th>
<th>TOODE</th>
<th>EAN</th>
<th>KOOD</th>
<th>ARVE</th>
<th>TK</th>
<th>XML</th>
</tr>
</thead>
<tbody>
<tr>
<td>369097</td>
<td>BENQ LED 21.5 GW2280 VA 0.248 FHD 1920x1080p 20M:1 (typ 3000:1) 250cd 178/178 5ms VGA/2xHDMI, TCO 7.0, Tilt, VESA, col: must</td>
<td>4718755073298</td>
<td>9H.LH4LB.QBE</td>
<td></td>
<td>1</td>
<td></td>
</tr>
<tr>
...
I have multiple CSV files and I need to automate it.
What I need is to add html tags around my .to_html conent. Right now Im doing it manually and that takes time.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="mycss.css">
</head>
<body>
<h1>Title</h1>
<h3>Secondary title</h3>
.to_html content
</body>
</html>
The output of .to_html() is simply a string. So prepend and append whatever boilerplate you like when writing HTML files. Apparently you already have a function that can suitably parse an input CSV, so do something like this:
import glob
import re
for infile in glob.glob('*.csv'):
outfile = re.sub(r'\.csv$', '.html', infile)
df = parse_csv(infile)
with open(outfile, 'w') as fout:
fout.write(PREAMBLE + df.to_html() + POSTAMBLE)
I'd recommend jinja2 for that, since compared to string concatenation, it's easier to debug later on. Here's how the code could look like:
EDIT: modified after comment
import os
import jinja2
# setup loader
templates_path = os.path.join(__file__, "../templates")
env = jinja2.Environment(loader=jinja2.FileSystemLoader(templates_path))
# get and fill the template
data_as_html = """<table border="0" class="dataframe">...</table>""" # from pandas
base_tmpl = env.get_template("base.html")
html = base_tmpl.render(data_as_html=data_as_html)
# write to disk
output_filename = os.path.join(__file__, "../out.html")
with open(output_filename, "w", encoding="utf-8") as f:
f.write(html)
With the template templates/base.html being something like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The output</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
{{ data_as_html }}
</body>
</html>
I am working on a static template and decided to use handlebars and gulp to generate the html part.
I have read several examples and I understand the concept of importing a partial like:
partial.hbs
<h1>Contents of the partial</h1>
index.hbs
<html>
<head></head>
<body>
{{> partial }}
</body>
</html>
which would yield:
<html>
<head></head>
<body>
<h1>Contents of the partial</h1>
</body>
</html>
What I can't seem to find is extending a base file instead of importing into it. What I mean is this:
base.hbs
<html>
<head></head>
<body>
{{ contents }}
</body>
</html>
index.hbs
{{extend base}}
{{ contents }}
<h1>Contents of the partial</h1>
{{ end contents }}
What is the proper way to do this in handlebars?