I am working on a django project that relies on angularjs and having trouble implementing angular-ui-router framework.
As mentioned in documentation I have included ui.router as a dependency,
app = angular.module('myApp',['restangular','ui.router',])
configured the states as follows,
app.config(['$stateProvider',function($stateProvider){
$stateProvider.state('landing',{
url: '/',
template:"<p> somethings here.</p>"
})
}]);
in base.html file i bootstrap the django project with angularjs as required
ng-app=myApp.
and in index.html which inherits base.html
<div ui-view>
<i>nothing here but this text</i>
</div>
my urls.py,
url(r'^$',home,name="homepage")
This does not work, ui-router never includes the inline template in index.html. index.html always loads nothing here but this text. I have looked at as much questions asked here but are not helping. What am I missing, is this specific to django?
I would say that these lines should make it:
app.config(['$urlRouterProvider',function($urlRouterProvider){
$urlRouterProvider.otherwise('/');
}]);
Check the working plunker here
Also check:
otherwise() for invalid routes
Related
I'm using Nunjucks apart from Jinja2 in my Flask application so I can pass in some variables through JS that I want to render in an HTML template.
-- Here's what I do --
JS controller:
this.element = DomHelper.htmlToDom( slideTemplate.render({ slide : this.model }));
{% include "presentation/slide/layouts/layout-1.html/" %}
What I have working:
Nunjucks compiles & render works properly without the {% include..}
slide variable is being passed and used fine
Any thoughts or suggestions would be nice. Thanks!
So I found that I had overlooked a simple thing. My nunjucks was configured to work only for the client side but the templates are served through flask. The relative path will only work for the client side data.
Solution: I placed the template layouts inside the static/ directory instead of in server-side templates/
Based on your question, you might have a typo. You have:
{% include "presentation/slide/layouts/layout-1.html" %}
but you say:
The desired html template I want to includes is in
templates/presentations/slide/layouts/ - Here's my folder structure
Is the path templates/presentations OR templates/presentation ?
Before posting this i've tried every solution method posted online, including solutions on Stackoverflow and Django. (I think the reason for error perhaps is due to the fact that i'm on a newer verison of jQuery and django and most solutions are dated, using jQuery 1.9 and django 1.5.1)
Here are some URL's to solutions that don't work:
Django CSRF check failing with an Ajax POST request
How to use $.post with django?
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
Any help would be appreciated. Another possibility for error is the fact that i'm not actually sure where to place these snippets exactly. So far i've pasted everything inside the jquery on document load, i've also tried pasting the code in the very start of the .js file. (My javascript code is fragmented in chunks, some are seperate .js files and some are inline with the html being rendered with django context, so any solutions with "{{ csrftoken }}" are bad.
Thanks!!
The CSRF token only gets set if it's present in the template or if the view is decorated with ensure_csrf_cookie(). Putting {% csrf_token %} in index.html will make it apply for all your pages.
From the docs:
The CSRF token is also present in the DOM, but only if explicitly included using csrf_token in a template.
...
If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie().
Can you try this:
$.ajax({
type: "POST",
url: '{% url "some_url_which_accepts_post" %}',
data: {'csrfmiddlewaretoken': '{{csrf_token}}', 'comment_id':1},
success: function(data, textStatus){
//something
},
});
I am trying to use url-names in my javascript/jquery files for AJAX requests and I have found several solutions that can solve this problem. The one that I am currently using is the following.
I define a url to serve javascript files:
urls.py
url(r'^js/([\w\.\-]+)/([\w\.\-]+)/$', 'views.get_javascript_file', name='get_javascript_file')
url(r'^getmoredicus/$', 'load_discussions', name="load-discus"),
Then I define the view that renders the javascript files.
views.py:
def get_javascript_file(request, app_name, js_file):
'''
Used to request and serve rendered javascript/jquery files.
'''
return render_to_response("%s/%s.js" % (app_name, js_file),
context_instance=RequestContext(request))
Now in the html files, we can use the get_javascript_file url to get the rendered javascript files.
html files:
<script type="text/javascript" src="{% url get_javascript_file 'myapp' 'jsfile' %}"></script>
Now in any javascript file, I can access the url-names through {% url url-name %}.
Questions:
1) Is there a better/faster way to use url-names in javascript files? I know that there are some apps already created to accomplish this but I want to get everyone's(django experts) opinion on the best way to accomplish this.
2) Can we cache the rendered javascript files after they have been rendered the first time so that in each subsequent request, we don't have to render them again? If yes, then how can we go about doing that.
3) In this method, we are rendering the script files from their apps folders. Is there a way to access the static files located in STATIC_ROOT from the get_javascript_file view? I am just thinking about how this would work in a production environment. Is it a good practice to access static files from their apps folders rather than putting them in STATIC_URL and accessing them from there?
NOTE
I know that there are already some questions on SO that answer some parts of this question, but I just wanted to get to the bottom of this once and for all for future django learners. What is the best way to use url-names in javascript or any script for that matter?
I'm not a fan of running external js through the view rendering. Especially if you're using something like django-compressor to compress and cache your js files.
I prefer to just include the variables in a script tag prior to including the external files.
<script>
my_var = "{{ MY_PROPERTY }}"
</script>
<script type="text/javascript" src="{{ STATIC_URL }}js/external_script.js"></script>
That solution is also not always ideal, but I'm open to other solutions.
I have a working backbone application. The backend is Django.
I have a Detail View of posts that uses an underscore.js template with a bit of logic:
For example:
{[ _.each(model.images, function(i){ ]} <img src="{{i.image}}"> {[ }); ]}
I now want to create the server-side view, in order to serve the url example.com/details/10
What would be the best way of reusing the underscore.js template? Or should I just copy/paste it into another file and change it to the django templating language?
Have a look here to get an idea of how you could efficiently structure such an application.
The django app is inside the blog directory(look at the static/app.js)
I'm running the developer's Django server while writing a simple view and it seems whenever I request a page, the console shows that there are 2 GETs for the same URL. What would cause this happen? I'm not using any redirects, so I don't see how a 2nd request would be made?
EDIT: It appears to be caused by the template. Changing to a blank html file for a template resolved the issue. The question is why? I have multiple {% if %} {% endif %} sections, with no elses. Could that be an issue?
It also could be Firefox following a WC3 directive under which it's supposed to dual load if certain tags come empty or broken, for example, a without a src="" etc. That being said, I saved off the rendered HTML on receipt and moved it into a static file, where I added the same headers as the real checkout and a small DB log of all accesses.
I just stumble upon this problem and fixed it removing my img wit src=""
Please confirm, if Django is redirecting after appending slash to your url. Its the property APPEND_SLASH in your settings.py controls that.
The second request is probably caused by a mis-configured asset link - a script, style or img tag which is empty or omits the initial / and is therefore re-requesting the page.
It could be your shortcut/favicon
Do you have link rel="shortcut icon" in your page template? Comment it out to see if it removes the second request
In my case : I have the same javascript code in 2 files : one in the base template and the same one in another template. As I use ajax to not reload all the page I got the call 2x, then 4x, and 8x, ...
The solution is the use the javascript code only in mybase.html
Hereafter my js code :
<script type="text/javascript">
// Code jQuery Ici
$(document).ready(function(){
// GET
$(".ajax_onglet_get").click(function(e){
var lien = $(this).attr('href');
$('#zone_travail').fadeOut('fast', function(){
$('#zone_travail').load(lien, function() {
$('#zone_travail').fadeIn('fast');
});
});
e.preventDefault()
});
});