Unable to use double braces to resolve variables [duplicate] - html

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>

Related

Can't Get Angular To Load Routes

I am making a local page following this tutorial, and it implements a login using django and angular. But I can't get the button register to show anything. It just changes the directory to /register. I think it has to do with routing. I get no errors. And I don't know how to debug this thing anymore, so I've run out of options. This is my first 'website'.
Reason this isn't going smooth is because I did not get the starter project the tutorial came with. I wanted to learn how to implement this from scratch. This means my packages are newer (bootstrap, django, etc). Let me know if you need any more info, please. Thanks.
/templates/index.html
<!DOCTYPE html>
<html ng-app="hawk">
<head>
<title>Hawk</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
{% include 'navbar.html' %}
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 ng-view"></div>
</div>
</div>
{% include 'javascripts.html' %}
</body>
</html>
/static/javascripts/hawk.routes.js
(function () {
'use strict';
angular
.module('hawk.routes')
.config(config);
config.$inject = ['$routeProvider'];
function config($routeProvider) {
$routeProvider.when('/register', {
controller: 'RegisterController',
controllerAs: 'vm',
templateUrl: '/static/templates/authentication/register.html'
}).otherwise('/');
}
})();
/static/javascripts/authentication/controllers/register.controller.js
(function () {
'use strict';
angular
.module('hawk.authentication.controllers')
.controller('RegisterController', RegisterController);
RegisterController.$inject = ['$location', '$scope', 'Authentication'];
function RegisterController($location, $scope, Authentication) {
var vm = this;
console.log("\n\nregister\n\n");
vm.register = register;
function register() {
Authentication.register(vm.email, vm.password, vm.username);
}
}
})();
/static/javascripts/hawk.js
(function () {
'use strict';
angular
.module('hawk', [
'hawk.routes',
'hawk.authentication',
'hawk.config',
]);
angular
.module('hawk.routes', [require('angular-route')]);
angular
.module('hawk.config', []);
angular
.module('hawk')
.run(run);
run.$inject = ['$http'];
function run($http) {
$http.defaults.xsrfHeaderName = 'X-CSRFToken';
$http.defaults.xsrfCookieName = 'csrftoken';
}
})();
/templates/javascripts.html
{% load compress %} {% load staticfiles %} {% compress js %}
<script type="text/javascript" src="{% static '../node_modules/jquery/dist/jquery.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/bootstrap/dist/js/bootstrap.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/bootstrap-material-design/dist/js/material.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/bootstrap-material-design/js/ripples.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/underscore/underscore.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/angular/angular.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/angular-route/angular-route.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/angular-cookies/angular-cookies.js' %}"></script>
<script type="text/javascript" src="{% static '../node_modules/ng-dialog/js/ngDialog.js' %}"></script>
<script type="text/javascript" src="{% static 'lib/snackbarjs/snackbar.min.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/hawk.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/hawk.config.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/hawk.routes.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/authentication/authentication.module.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/authentication/services/authentication.service.js' %}"></script>
<script type="text/javascript" src="{% static 'javascripts/authentication/controllers/register.controller.js' %}"></script>
{% endcompress %}
/static/javascripts/authentication/services/authentication.service.js
(function () {
'use strict';
angular
.module('hawk.authentication.services')
.factory('Authentication', Authentication);
Authentication.$inject = ['$cookies', '$http'];
function Authentication($cookies, $http) {
var Authentication = {
register: register
};
return Authentication;
function register(email, password, username) {
return $http.post('/api/v1/accounts/', {
username: username,
password: password,
email: email
});
}
}
})();
/HawkProject/urls.py
from django.contrib import admin
from django.urls import path, re_path, include
from rest_framework_nested import routers
from authentication.views import AccountViewSet
from HawkProject.views import IndexView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^api/v1/', include(router.urls)),
re_path(r'^.*$', IndexView.as_view(), name='index')
]
Although its not an answer to this question precisely but its an answer with a diff approach
The tutorial you have provided is too long and not included with video. I have worked on Django and AngularJS to create an ecommerce website. I'l suggest you not to mix Django and AngularJS as much as you can to avoid conflicts. That being said, I'll provide you what I implemented for User Registration in brief:
I kept User form separate from AngularJS forms because Django has its own way to handle User Management (Sign in,sign Up, session (using #login_required) etc).
I provided Register on the nav-bar. (Note: /signup is a url mapped in urls.py file)
<form name="regForm" class="form-signup" action="/sign_up/" method="post" role="form" onsubmit="return validateForm()">
{% csrf_token %}
{{form.errors.values.0}}
<div class="form-group reg-username" id="fname">
<div>
<input name="first_name" class="form-control input" size="20" placeholder="Enter First Name" type="text" required>
</div>
<p id="fname-error" class="help-block"></p>
</div>
<div class="form-group reg-username">
<div>
<input name="last_name" class="form-control input" size="20" placeholder="Enter Last Name" type="text" required>
</div>
</div>
<div class="form-group reg-email">
<div>
<input name="email" class="form-control input" placeholder="Enter Email" type="email" required>
</div>
</div>
<div class="form-group reg-password" id="pwd1">
<div>
<input name="password1" class="form-control input" placeholder="Password" type="password" required>
</div>
<p id="pwd-error1" class="help-block"></p>
</div>
<div class="form-group reg-password" id="pwd2">
<div>
<input name="password2" class="form-control input" placeholder="Confirm Password" type="password" required>
</div>
<p id="pwd-error2" class="help-block"></p>
</div>
<input name="submit" class="btn btn-block btn-lg btn-primary" value="REGISTER" type="submit">
</form>
Where url(r'^sign_up/', ('ecommerce.views.register_user')),
In the views.py
#sensitive_post_parameters()
#csrf_protect
#requires_csrf_token
def register_user(request):
args = {}
args.update(csrf(request))
if request.method == 'POST':
if not verify_google_recaptcha(request.POST):
return HttpResponse(get_status_response('Failure', 'Are you sure you are not a robot?'))
else:
logger.info('Recaptcha passed !!!')
form = RegistrationForm(request.POST)
msg = 'register'
args['form'] = form
if form.is_valid():
try:
# username = form.cleaned_data['username']
email_obj ={}
email_obj['email'] = form.cleaned_data['email']
email_obj['first_name'] = form.cleaned_data['first_name']
email_obj['last_name'] = form.cleaned_data['last_name']
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
activation_key = hashlib.sha1(salt + email_obj['email']).hexdigest()
email_obj['activation_link'] = ACTIVATION_LINK.format(activation_key)
template = get_template('RegistrationLink.html')
context = Context({'email': email_obj})
content = template.render(context)
emsg = EmailMultiAlternatives('Activation link for {0}'.format(DEFAULT_DOMAIN) , content, DEFAULT_FROM_EMAIL, to=[email_obj['email']])
emsg.attach_alternative(content, "text/html")
emsg.send()
form.save() # save user to database if form is valid
# Get user by username
user = SiteUser.objects.get(email=email_obj['email'])
# Create and save user profile
new_profile = UserProfile(user=user, activation_key=activation_key,
key_expires=settings.EXPIRATION_DAYS)
new_profile.save()
except Exception as e:
logger.exception(e)
return render_to_response('500.html')
# return HttpResponseRedirect('/register_success')
return render_to_response('confirm.html', {'msg': msg})
else:
args['form'] = RegistrationForm()
return render_to_response('userRegistration.html', args, context_instance=RequestContext(request))
Note: The code written in def register_user is core Djnago feature to handle user registration which I am exploiting. You can get these over internet
If you need to render any form such as Order address, then create a form of angular and simple pass the value to Django using $http (the /url_called from $http will be mapped in urls.py).
Make sure you are using {% verbatim %} and {% endverbatim %} whenever you are using {{ some_angular_variable }} because it contradicts withDjango Templatesyntax. Better to go forng-bind` as much as you can.
Ignore $locationProvider for now if you are in initial stage. You'll get some issues when using that with Django. I have a solution for that as well but for beginner, dont get into that. Try to integrate the plunkr code in your Django app and see if it's working. Start small, dont jump to complicated examples.
Check one basic example of ngRoute.
In case you get stuck, post another question and put the link in the comment so that I can help you in that as well

I don't see the expected view in angular JS, maybe binding issue?

So I am trying to build the simplest Angular JS application and no idea what I am doing wrong.
It is made of 4 files:
index.html - which I use like a layout to display main.html
app1.js - used for defining simple routing rules like /main should redirect to main.html in combination with MainController; when it doesn't find a valid path, revert to a default which equals the previous path
MainController.js - I just have some timer functions here
main.html - displays a search button and search textbox
For some reason, I can't see mainvtemplate from my index.html which should redirect me to /main.
Here is the code:
index.html file
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="angular-route#*" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
<script src="MainController.js"></script>
</head>
<body>
<h1>Github Viewer</h1>
<div ng-view></div>
</body>
</html>
the app1.js
(function(){
var app = angular.module("githubViewer", ["ngRoute"]);
app.config(function($routeProvider){
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({redirectTo:"/main"});
});
}());
the main.html file:
<div>
{{ countdown }}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>
You may ignore the countdown, this is a timer created in MainController.js. I render its simplified logic:
(function() {
var app = angular.module("githubViewer");
var MainController = function($scope, $interval, $location) {
$scope.search = function(username) {
if(countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
$location.path("/user/" + username);
};
$scope.countdown = 5;
};
app.controller("MainController", MainController);
}());
Isn't weird I'm not able to see the search button and search textbox? Maybe I am missing sth really obvious here.
in your index.html
<script src="app.js"></script>
replace with
<script src="app1.js"></script>
main.html
<div ng-app="githubViewer" ng-controller="MainController ">// add ng app ang nd cntroller
{{ countdown }}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>

go - Render html/template with inheritance

I have two html templates, with index.html extending base.html
base.html is like this:
{{ define "base" }}
<html>
<head>
<meta charget="utf-8">
<title>{{ template "title" . }}</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/isotope.pkgd.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
{{ template "index" . }}
</body>
</html>
{{ end }}
And index.html:
{{ define "title" }}Homepage{{ end }}
{{ define "index" }}
<div class="wrapper">
<div class="page-content">
<div class="container">
<div class="left">
<img src="../public/images/img_landing_page_mac.png">
</div>
<div class="right">
<h2 style="font-size: 33px; letter-spacing: 5px">Organize <br>Modern Knowledge<br> for Mankind</h2>
<p style="font-size: 20px;margin-top: 35px;letter-spacing: 4px">Consume, Colect and Revisit <br>Knowledge at Your Fingertips</p>
<img src="../public/images/btn_get_chrome.png">
</div>
</div>
</div>
</div>
{{ end }}
It should render when requesting path on browser with a callback handler:
func IndexHandler(w http.ResponseWriter,r *http.Request){
files:=[]string{"base","index"}
util.RenderTemplate(w,nil,files...)
}
RenderTemplate is a wrapper function to render
func RenderTemplate(w http.ResponseWriter,data interface{},tmpl... string){
cwd,_:=os.Getwd()
files:=make([]string, len(tmpl))
for i,file:=range tmpl{
files[i]=filepath.Join(cwd,"./view/"+file+".html")
}
t,err:=template.ParseFiles(files...)
if err!=nil{
http.Error(w,err.Error(),http.StatusInternalServerError)
return
}
templates:=template.Must(t,err)
err=templates.Execute(w,data)
if err!=nil {
http.Error(w,err.Error(),http.StatusInternalServerError)
}
}
After I start server, I request that path on browser, but nothing is rendered at all. What am I missing? It seems that no inheritance is comprehended here
I follow this tutorial, trying to render templates with inheritance / extension:
https://elithrar.github.io/article/approximating-html-template-inheritance/
The define action doesn't execute template, only template and block actions do. Most probably you just want to remove define from your base template (first and last lines) and it will work as expected.
Or you can use Template.ExecuteTemplate function instead of Template.Execute. It accepts name of the template:
err = templates.ExecuteTemplate(w, "base", data)
Or if you are using Go1.6 or newer you can try block action instead of define.
On the side note, please, consider using gofmt.

Django not working with Angularjs

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!

CSS styling not showing up on Django app

I have my CSS in the following path: mysite/myapp/static/myapp/style.css. As of now, the CSS is simply:
body {
background-color: #F2B8F0
}
h1 {
color: #7BE0CB
}
I have my HTML set up like this: mysite/myapp/templates/myapp/home.html, where the following code is up on top:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'myapp/style.css' %}" />
My settings.py is like:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
However, nothing happened, and the different text and background colors aren't showing up in my HTML. Does anyone happen to know why? Thanks!
Perhaps your css link tag is in the incorrect spot within your HTML. It should be as follows:
<!DOCTYPE html>
{% load static %}
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static 'myapp/style.css' %}" />
</head>
<!-- YOUR HTML HERE -->
</html>
let
{% load static %}
be your first line in your HTML