{{ form.media.js }} and {{ form.media.css }} are great to easily include media in Django templates.
My problem is that I would like to get access to the raw urls (without <\script type="text/javascript" src="raw_url"><\/script>) of these media (to include them using headjs).
I'd like to achieve something like that:
<script>
{% for script in form.media.js %}
head.js("{{ script.raw_url }}");
{% endfor %}
</script>
If you take a look at source code of Media class there will be a function:
def render_js(self):
return [u'<script type="text/javascript" src="%s"></script>' % self.absolute_path(path) for path in self._js]
So you can go the same way. Since we can't use underscored attributes in templates we can add method to the form class like this and use it:
from django import forms
class TestForm(forms.Form):
def get_media_js(self):
return [self.media.absolute_path(path) for path in self.media._js]
Related
So this is my issue: I have a Python string that contains both HTML and Django Template Tags and want to inject it into a base HTML file when I go to that page. Although, when I go to the page, all the HTML renders, but the Django Template Tags do not, and are treated literally as strings?
Here is a simplified example of the issue:
Views.py
def page(request, code):
html = {
'code': code
'html': """<p>Hello world {{ code }}</p> <script src="{% static 'appName/javascript_code_example.js' %}"></script>"""
}
return render(request, 'base.html', html)
base.html
{% load static %}
...
{{ html | safe }}
...
And all I will see when I run the app on my local machine with python3 manage.py runserver and go to the URL that renders base.html is Hello world {{ code }}, and the Javascript code is not executed. Instead of {{ code }} I'd like to see the actual value of the 'code' key in the html dictionary in the Views.py file.
If my base.html file is as follows:
{% load static %}
...
<p>Hello world {{ code }}</p>
<script src="{% static 'appName/javascript_code_example.js' %}"></script>
...
Then the Javascript will be enabled and I will see Hello world value_of_code_variable on the screen.
you have to load the python script that has the template library functions.
Also, Why are you rendering a string into html as opposed to creating an html template? (html file with template syntax)?
The Django template engine will not render (parse) template code inside injected strings. For this to happen, you have to manually render the template code by either:
instantiating a Template object and passing the resulting string to your base.html,
or ideally by moving the value of your html context variable to a template file, and using render_to_string().
If you decide to go for the last one, you should definitely consider using the include template tag in your base.html (instead of manually rendering using render_to_string()), as it reduces the amount of manual work and is the preferred way of rendering template code inside another template.
You can use file writing to do this task.
Make a newfile.html in templates folder and you can do thusly
Views.py
html_tag = "{% extends \"yourapp/base.html\"%}"+"{% block content %}"
html_tag +="<p>Hello world {{ code }}</p> <script src=\"{% static \"appName/javascript_code_example.js\" %}\"></script>"
html_tag +="{% endblock content %}"
html_file = open('yourapp/templates/yourapp/newfile.html', "w")
html_file.write(html_tag)
html_file.close()
html = {
'code': code
}
return render(request, r'yourapp\newfile.html', html)
In base.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Your base code</p>
<!--The part of code you want to retrieve from views.py file-->
{% block content %}{% endblock content %}
</body>
</html>
What I'm looking to do is package templates in a Django package which can be inserted on a developers page by simply using
{% load app_tags %}
this works find for custom methods which take a value and return a value. What I would like to do is simply have a method which returns a template packaged with the app.
{{ custom_template }}
So the question boils down to how do I have a project which installs my app load my apps' tags and call a tag method which includes a template from the app.
thank you for any responses.
yup! make an inclusion tag in app_tags.py, and then call it!
they're great for code reuse (along with Django blocks and the {% include ... %} template tag, of course)
reference: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags
# app_tags.py
from django import template
register = template.Library()
#register.inclusion_tag("templates/myappname/greeting.html")
def greet(name, end="!!!"):
return { 'name': name, 'end': end }
and
{# templates/myappname/greeting.html #}
<h1> What's up {{ name }}{{ end }} </h1>
then to call this, you'd use {% and %}, the double bracket notation e.g. {{ custom_template }} is really only for showing the value of a single variable
{% load app_tags %}
{% for person in people_to_greet %}
{% greet person %}
{% end %}
<h3> cool greetings above ^ </h3>
i am using django endless pagination . its working normally that just shows the numbers at the bottom .
but, i tried to integrate twitter style into it:
http://django-endless-pagination.readthedocs.org/en/latest/twitter_pagination.html#pagination-on-scroll
I have followed exactly but didnt work .
When I looked at the js code, i have seen they have used .endless_more in js class, but the generated html file has only two classes for links :
1)endless_page_current
2)endless_page_link
but they used a.endless_more in js.
Can you tell me the correct way to implement?
Thanks
Views :
from endless_pagination.decorators import page_template
#page_template("my_index_page.html")
def myview(request,template='my_index.html', extra_context=None):
data = {}
if extra_context is not None:
data.update(extra_context)
myobj = Myobj.objects.all()
data['myobj'] = myobj
return render_to_response(template, data, context_instance=RequestContext(request))
Template :
my_index.html
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}js/endless.js"></script>
<script src="{{ STATIC_URL }}js/endless_on_scroll.js"></script>
{% include page_template %}
my_index_page.html
{% load templatetags %}
<center>
<div>
{% load endless %}
{% paginate myobj %}
{% for obj in myobj %}
{{ obj.name }}
{% endfor %}
{% show_pages %}
</div>
<center>
Here, I seriously beleive that i need to add some classes like endless_more , which the django-endless-documentation missed.
i'm using that on my portal, and it seems fine your code, you just missed one thing
{% show_more %}
that's what actually enables the twitter-style infinite pagination
edit here:
you may want to add this too:
<script type="text/javascript" charset="utf-8">
var endless_on_scroll_margin = 20;
</script>
where "20" is the number of pixels (from the bottom of the page) that triggers the scrolling
you may want to try more than one value till you get the perfect one for your project
see here and here
I know this isn't exactly Django templating philosophy, but i'd like to be able to include different templates depending on a list of plugins that I've specified in the http response context. For example, if I have the following plugins configured:
context['plugins'] = ['weather']
I attempt to include each template in the base template file:
{% for custom_plugin in custom_plugins %}
{% include "map/plugins/custom/{{ plugin }}/includes.html" %}
{% endfor %}
I've also tried:
{% for plugin in plugins %}
#register.inclusion_tag("map/plugins/custom/{{ plugin }}/includes.html", takes_context=True)
{% endfor %}
For now the each plugin will only contain script references and css classes in their includes.html file:
<script type="text/javascript" src="{{ MEDIA_URL }}map/js/plugins/custom/weather/weatherStation.js?ver={{ version }}"></script>
Any suggestions?
Your first way seems the best, and this answer might provide some pointers as to how you'd go about it: How to concatenate strings in django templates?
You basically want to build a string of the template to include in a variable with the with tag, then include it.
I have a model with an HTMLField which can be edited with a TinyMCE control in the admin. However, I would like to be able to give different options to TinyMCE depending on which instance of the model is being edited. How can I do this?
(For example, if the user is editing the SimplePage instance whose slug is technologies, I want TinyMCE to use the default CSS file, but if its editing the SimplePage whose slug is ticker, I want to use a different CSS file.)
I guess you have a Media class in your ModelAdmin with additional JavaScript and CSS for the admin (like here). Your JavaScript doesn't know the slug of the current object, let's change that.
First create one of the following directory structures in your templates directory: "admin/your-app" for an app or "admin/your-app/your-model" for a specific model only (see the Django documentation).
Then create a file "change_form.html" in that directory and put something similar to this in there:
{% extends "admin/change_form.html" %}
{% block extrahead %}
<script type="text/javascript" charset="utf-8">
var MYAPP_objectSlug = "{{ original.slug|escapejs }}";
</script>
{{ block.super }}
{% endblock %}
This will extend the usual "change_form.html" of the admin and extend the extrahead block to set a JavaScript variable with your object slug (original is your object).
Now adapt the JavaScript file that does the tinyMCE.init to use a different CSS file based
on the JavaScript variable MYAPP_objectSlug.
if (MYAPP_objectSlug == "ticker"){
var MYAPP_cssFile = "../css/special.css"; // change to your path
} else {
var MYAPP_cssFile = "../css/default.css"; // change to your path
}
tinyMCE.init({
...
content_css : MYAPP_cssFile,
...
});