Angular and django integration - django

I'm writing application with django and angular and I have following problem. After authentication in django I turn mvc view with angular app definition.
<div class="main">
<div class="main-inner">
<div class="container" ng-app="povos" ng-view>
{% block content %}{% endblock %}
{% block scripts %}{% endblock %}
</div>
</div>
</div>
<script src="/static/assets/js/bootstrap.js"></script>
<script src="/static/assets/js/angular.js"></script>
<script src="/static/assets/js/angular-route.js"></script>
<script src="/static/assets/js/angular-cookies.js"></script>
<script src="/static/spa_app/app.js"></script>
<script src="/static/spa_app/modules/messages/messages.module.js"></script>
My app.js looks like that:
angular.module('povos', ['povos.messages'])
And my messages module like following:
angular.module('povos.messages', ['ngRoute'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/messages', {
templateUrl: 'messages.html'
})
}])
My problem is that if I return that view and I try to request to /messages path I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/messages
Using the URLconf defined in povos.urls, Django tried these URL patterns, in this order:
(urls here)
The current URL, messages, didn't match any of these.
My browses call to django mvc app. I understand in this way. Is it possible not to call django only work on angular routeProvider? How to configure it? Sorry for my english but It is not my native language.

You are serving the page through Django, so first ensure /messages/ is available in urls.py of Django.
After the root page and AngularJS files are loaded successfully, Angular starts to aware the URL:
by default it's in the hash form, thus only when the URL is /messages/#/messages, can the Angular router match the URL and render message.html.
/messages/#/messages
^ ^ ^ ^
| | | |
| | |Angular Part
|Django Part

Related

Is it possible to load bootstrap modal directly with flask

In flask we can render a page using render_template('home.html, data=data).
In the same way is possible to load bootstrap modal without having to use javascrpt?
For e.g if an element is clicked in the page,
<span class="example" data-toggle="modal" data-target="#showExample" Testing</span>
A call is made to function in flask function and it trigger the modal pop-up and pass data that can used to populate field
If i'm understand what you mean, you can do this in JavaScript (just paste it in bottom of your page, in the tag "script":
document.getElementById('showExample').addEventListener('click', function() {
// Do some stuff, that you need to do...
});
Or, if you want, you can do this without JavaScript (i guess that you using Jinja2):
Insert it into your page template:
{% if show_example_modal %}
<span class="example" data-toggle="modal" data-target="#showExample" Testing</span>
{% endif %}
Python view code:
#app.add_route('/something/')
def something():
return render_template("something.html", show_example_modal=True)

how to load correctly addthis widget js?

I'm development a blog using django and I have included the addthis tool for include the share buttons. I'm including the addthis buttons in the posts detail page. I need to get the facebook shares count for the current blog post deetail. I'm using these steps, but I'm gettin this error in the console: ReferenceError: addthis is not defined.
The addthis code is loaded remotely then, I think that my js is not running because it runs before the addthis script load is complete. How can I fix it?
{% block js %}
<script type="text/javascript"src="//s7.addthis.com/js/300/addthis_widget.js#pubid=fdfs" async="async"></script>
<script src="{% static 'js/blog/blog_list.js' %}"></script>
<script>
$(function () {
addthis.sharecounters.getShareCounts('facebook', function(obj) {
console.log(obj);
});
})
</script>
{% endblock %}
You can wrap your function around window.load like below
$(window).load(function() {
addthis.sharecounters.getShareCounts('facebook', function(obj) {
console.log(obj);
});
})
This will ensure that the code will get executed once entire window is loaded. For further reading read this.

How to get django_hitcount app working with Mezzanine blog

Been trying for several hours now.
I set up according to instructions but I can't get it to count hits on a blog post.
/blog/blog_post_detail.html
{% load .. .. .. hitcount_tags %}
.
.
.
.
{% block blog_post_detail_content %}
<script type="text/javascript">
$(document).ready(function() {
{% get_hit_count_javascript for blog_post %}
});
</script>
{% get_hit_count for blog_post %}
.
.
.
{% endblock %}
And in my urls.py I added:
url(r'^blog/ajax/hit/$', update_hit_count_ajax, name='hitcount_update_ajax'),
Looking at page source in browser the javascript does appear to run.
$(document).ready(function() {
var csrf = $('input[name=csrfmiddlewaretoken]').val();
$.post( '/blog/ajax/hit/',
{ csrfmiddlewaretoken: csrf, hitcount_pk : '1' },
function(data, status) {
if (data.status == 'error') {
// do something for error?
}
},
'json');
});
But it's not counting. So I'm not quite sure why it doesn't count a page hit.
Figured it out. In Mezzanine you have to put custom url patterns above the
("^", include("mezzanine.urls")),
pattern otherwise they will be ignored.

Ember template and Google AdSense

What is the appropriate way to include a Google AdSense banner in an Ember (Handlebars) template?
Say I have a template for a view that looks like this:
<script type="text/x-handlebars" data-template-name="myPageWithBanner">
<div id="mainContent">
Lorem ipsum main content
</div>
<div id="banner">
//Normally I would insert a script tag here, but that is not possible
</div>
</script>
Do I need to do this from code using pre-compiled templates, or is there a way I am not aware of?
I don't have a Google AdSense account, so I can't test this. But there are several major problems here:
You can't include a <script> tag inside a Handlebars template, not even if you use CDATA.
Google AdSense requires the AdSense JavaScript to appear verbatim in your page, or it's a TOS violation.
According to this StackOverflow answer, AdSense on AJAX sites is poorly supported at the moment.
The Google AdSense crawler won't be able to see any content on your page, so I doubt that ad-targeting is going to work. But see below for some things which might help crawlers.
But I'm going to assume, for the sake of simplicity, that you can discuss TOS issues directly with Google, and I'll just try to solve the technical problems. First, based on this StackOverflow answer, here's one possible solution that allows you to serve up Google's script verbatim:
<script type="text/x-handlebars">
<h1>Ember AdSense</h1>
{{outlet}}
<div id="ads"></div>
</script>
<script type="text/x-handlebars" data-template-name="index">
<p>Hello, world!</p>
</script>
<div id="ads-load" style="display: none">
<!--
Apparently this needs to appear verbatim, exactly as Google gave it to
you, or it's a TOS violation.
-->
<script type="text/javascript"><!--
google_ad_client = "ca-pub-XXXXXXXXXX";
/* Test Ad */
google_ad_slot = "XXXXXX";
google_ad_width = 250;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
Then when our main template loads, we use jQuery to move the ads into our application template:
window.App = Ember.Application.create();
// Explicitly declare the view class for our application view.
App.ApplicationView = Ember.View.extend({
// Called once the view is rendered.
didInsertElement: function () {
$('#ads-load').appendTo("#ads").css("display", "block");
}
});
As for allowing the Google crawler to see you content, Google has official advice for AJAX applications, but I don't know whether that works with the AdSense crawler. Alternatively, if you're using pushState to update your displayed URLs, then you need to make sure that each of those URLs can be rendered by your server when requested by a crawler. (The Discourse forum software does exactly this.)
Please let me know if it gets you any closer.

how to refresh in a div values from a model with jquery .ajax() to django

I have a view which returns a chained object of 3 models
def test(request):
output=itertools.chain(
model1.objects.all(),
model2.objects.all(),
model3.objects.all()
)
return render_to_response('test.html', {'output':output})
In the html, I added an anchor and a jQuery script, which should replace the #output with new values just from model1
<html>
<head>...</head>
<body>
<script>
$(document).ready(function() {
$("#switch").click(function() {
$.ajax({
url: $(this).attr("href"),
success: function(result) {
//whatever I put here is not triggered
}
});
});
});
</script>
<a id="switch" href="?model=1">switch to model 1</a>
<div id="output">
{% for item in output %}
<div id="{{item}}">
{{item}}
</div>
{% endfor %}
</div>
</body>
</html>
I tried to put the div#output into a separate template output.html and modified the views.py like so:
def test(request, template='test.html'):
if request.GET.get('model'):
output=model1.objects.all()
else:
output=itertools.chain(
model1.objects.all(),
model2.objects.all(),
model3.objects.all()
)
if request.is_ajax(): template='output.html'
return render_to_response(template, {'output':output})
But everytime I click the link, the whole page is refreshed (with the new values from model1).
Opera returns just the output.html
Been struggling with this for more than 3 days, Im new into Ajax and this is getting very confusing for me.
I hope someone can shed some light!
First, make sure that your view works and that you're getting the expected HTML output when accessing the url directly (you might also want to comment out if request.is_ajax() temporarily).
Then, try replacing the content of the #output div using jQuery.html() method in your ajax call. Here is an example with some animation:
$.ajax({
...
success: function( returnedData ) {
$("#output").css("color", "red").fadeOut(500, function() {
$("#output").html(returnedData);
$(this).css("color", "green").fadeIn(500);
});
}
Also, try monitoring your ajax call using Firebug/Chrome Developer Tools - both tools will allow you to quickly determine the issue.
Thanks to Daniel Rosman for the heads-up I had to prevent the default action of the a#switch. It works like butter now!
Here is the initial question: how to access jQuery.ajax() get parameters in Django views