It was based in:
http://djangosnippets.org/snippets/1586/
Instead of doing this:
'attribute_name = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))`
You can do this in your template:
{{ form|cssclass:"attribute_name:special_class"|cssclass:"other_attribute:special_class" }}
This example assumes you have a form and want to highlight one of two fields
by setting <class="highlight"> in the html dynamically. This is an alternative to
<https://docs.djangoproject.com/en/1.3/ref/forms/widgets/#customizing-widget-instances>,
but now you're not limited to assigning the class to the fields html-output,
instead you can also assign it to a div around the field like done here.
After assigning a css-attribute to a field, we access the css via a templatefilter
*{{ field|css }}*
that looks up
*field.form.fields[field.name].css*
and not simply *field.css*, since the latter would try to access
a non-existing css-attribute on a BoundField-instance
EDIT:
The templatefilter is unnecessary. There is a much easier way, since the original field itself is an attribute of the BoundField named 'field'. So in the template, we can access the css via {{ field.field.css }}. Thanks to Tom Evans for pointing me at this.
uses the system or specified locale to format a number. a css class called 'negative' would be added if the format is negative and the minus symbol would be replaced if it is the last char.
The admin site uses a CSS class for each kind of field so that they can be styled easily. This snippet gives ModelForms a similar feature.
See also: [James Bennett's explanation of formfield_callback](http://stackoverflow.com/questions/660929/how-do-you-change-the-default-widget-for-all-django-date-fields-in-a-modelform/661171#661171)
This Snippet allows a view to controle the printed forms on the templates, in a similar way to the fieldsets used by the django admin.
How to Use:
In the view in question, put:
def some_view(request):
...
fieldsets = (
(u'Title 1',
{'hidden' : ('field_1', 'field_2',),
'fields' : ('field_3',)}),
(u'Title 2',
{'hidden' : ('field_5', 'field_6',),
'fields' : ('field_4',)}),)
)
return render_to_response('some.html', {'fieldsets': fieldsets})
fieldsets = (
(None,
{'hidden' : ('evento', 'colaborador',),
'fields' : ('acompanhantes',)}),
)
Next, in the html just add:
<form enctype="multipart/form-data" id="edit" method="post" ...>
...
{% include "inc/form_snippet.html" %}
...
<input type="submit" value="Submit">
</form>
Active class for navigation link
{% navclass default current url %}
First argument is the default class and second is the current class
Third argument is the url name(s) of the page
example: <a class="{% navclass leftnav curentnav name1,name2 %}" href="/about/">
A lot of times we need to insert a specific **CSS class** into a Form instance for it to be rendered in the template.
The current method is to specify the CSS class in the Python code through the form field widget. But it would be easier for the designer to be able to specify the CSS class in the template directly.
For example rather than doing this in your Python code:
'name = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))`
You can do this in your template:
`{{ form.name|cssclass:"special"}}`
This template filter only works with Form Field instance.
If you have this as your base class for all unit tests you can do the following:
class TestViews(BaseTestCase):
def test_generated_stats(self):
"test that certain stuff in the response"
...create some content for testing or use fixtures...
response = self.client.get('/some/page/')
# At this point response.content is a huge string filled with HTML tags and
# "junk" that you don't need for testing the content thus making it difficult
# to debug the generated HTML because it so huge.
# So we can zoom in on the <div id="stats>...</div> node
html = self._zoom_html(response.content, '#stats')
# the variable 'html' will now be something like this:
"""
<div id="stats">
<p>
<strong>2</strong> students<br/>
<em>1</em> warning.
</p>
</div>
"""
# This makes it easier to debug the response and easier to test
# against but the HTML might still be in the way so this would fail:
self.assertTrue('2 students' in html) # will fail
# To strip away all html use _strip_html()
content = self._strip_html(html)
# Now this will work
self.assertTrue('2 students' in content) # will work
It works for me and I find this very useful so I thought I'd share it.
This TemplateTag simply returns a True when it is Naked CSS Day allowing you to hide your CSS or display a custom message on that date. Allows allows for parameters should the date change (again).
Inspired by [http://www.djangosnippets.org/snippets/712/](YUI Loader as Django middleware)
This loads in css and javascript files where you want them (usually in the head) - but allows you to put them anywhere in your code - i.e. in a TemplateTag.
so your head code will look like this:
`
<head>
...
<!-- HEAD_init -->
...
</head>
`
then somewhere in your templates you can load in javascript or css files like so:
`
<!-- HEAD_include myfile.js myotherfile.css -->
`
It automatically checks if you've already included the files, and only puts them in once.
It automatically figures out if its a javascript or css file by the file name -
If you have an irregular filename (i.e. a google maps api script url) you can force it by using either of the following tags:
`
<!-- HEAD_include_js [my javascript file] -->
<!-- HEAD_include_css [my css file] -->
`
Or you can write inline code to get rendered in the head:
`
<!-- HEAD_render
<script>
someJavascriptCall();
</script>
-->
`
Todo: make it compress the js into one file...
This should work as a `django.views.generic.list_detail` generic view but will produce PDF version of given template.
This code is merged code from perenzo's [example](http://www.djangosnippets.org/snippets/659/) and code from `django.views.generic.list_detail` module.
`pisa` package is required from (http://www.htmltopdf.org/download.html) with `html5lib` package and Reportlab Toolkit 2.1+
NOTE: this is code for Django 0.96. In Django 1.0 change in line 3: ObjectPaginator to Paginator
Best practice based on [YSlow recommendations](http://developer.yahoo.com/yslow/), add the following to your Apache config for your media directory.
<Directory /home/.../site_media/>
...
FileETag None
ExpiresActive on
ExpiresDefault "access plus 10 years"
AddOutputFilterByType DEFLATE text/css application/x-javascript
</Directory`
Make sure to enable mod_deflate and mod_expires.
Here is a Django template tag that allows you to create complex variables specified in JSON format within a template.
It enables you to do stuff like:
{% var as person %}
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}
{% endvar %}
<p>{{person.firstName}}, </br>
{{person.address.postalCode}}, </br>
{{person.phoneNumbers.1}}
</p>
This tag also enables me to do dynamic CSS using as follows:
# urlpatters
urlpatterns = patterns('',
(r'^css/(?P<path>.*\.css)$', 'get_css'),
)
#views
def get_css(request, path):
return render_to_response('css/%s' % path, {},
mimetype="text/css; charset=utf-8")
# dynamic css within in /path/to/app/templates/css'
{% load var %}
{% var as col %}
{
"darkbg": "#999",
"lightbg": "#666"
}
{% endvar %}
{% var as dim %}
{
"thinmargin": "2em",
"thickmargin": "10em"
}
{% endvar %}
body {
background: {{col.darkbg}};
margin: {{dim.thinmargin}};
}
This is an extract of an example for use of "pisa" <http://www.htmltopdf.org> in "django". It shows the easiest way possible to create PDF documents just using HTML and CSS. In "index" we see the definition of the output of a form in which HTML code can be typed in and then on the fly a PDF will be created. In "ezpdf_sample" we see the use of templates and contexts. So adding PDF to your existing Django project could be just a matter of some lines of code.