This is a [Django template tag](http://www.djangoproject.com/documentation/templates_python/#extending-the-template-system "Extending the template system") that renders an arbitrary block of text with Markdown and [Pygments](http://pygments.org "Syntax highlighter").
Use Markdown as usual, and when you have a code block to insert, put it inside `code` tags, with the language as the class:
`<code class='python'>print "Hello, World"</code>`
To use it in a template, first `{% load ... %}` the tag library, then `{{ content|render }}` your content.
The tag takes one optional argument, to enable safe rendering in markdown. To use it, call `{{ content|render:"safe" }}`.
Mask an email address by removing most of the first portion and replacing it with "..."
For example. If you have a variable in your template context named `email_address `, and its value is "[email protected]"
{{ email_address|mask_email }}
will render as:
[email protected]
If the part preceding @domain.com is shorter than 5 characters, only the first letter will be used, followed by "...". So if we have "[email protected]"
{{ email_address|mask_email }}
will render as:
[email protected]
This is a really useful function I used to create the resized preview images you can see on the [homepage of my site](http://www.obeattie.com/). Basically, it takes the original URL of an image on the internet, creates a resized version of that image by fitting it into the constraints specified (doesn't distort the image), and saves it to the MEDIA_ROOT with the filename you specify.
For example, I use this by passing it the URL of a Flickr Image and letting it resize it to the required size, and then saving it to a local path. It then returns the local path to the image, should you need it. I however just construct a relative URL from the image_name and save that to the database. This way, it's easy to display this image.
Hope it's useful!
This tag can be used to calculate a python expression, and save it into a template variable which you can reuse later or directly output to template. So if the default django tag can not be suit for your need, you can use it.
How to use it
{% expr "1" as var1 %}
{% expr [0, 1, 2] as var2 %}
{% expr _('Menu') as var3 %}
{% expr var1 + "abc" as var4 %}
...
{{ var1 }}
for 0.2 version
{% expr 3 %}
{% expr "".join(["a", "b", "c"]) %}
Will directly output the result to template
Syntax
{% expr python_expression as variable_name %}
python_expression can be valid python expression, and you can even use _() to translate a string. Expr tag also can used context variables.
simple middleware and context processor for session-based messaging with types
Heavily inspired by patches on ticket 4604. Differs in that in this a notification
has type.
Installation:
* add notifications.NotificationMiddleware to MIDDLEWARE_CLASSES
* and notifications.notifications to TEMPLATE_CONTEXT_PROCESSORS
That assumes notifications.py is on pythonpath. If notifications.py lives in
your project dir, prefix those with '(projectname).'
Example use:
* request.notifications.create('Some bland information message.')
* request.notifications.create('Some more exciting error message.', 'error')
Example template code:
`{% if notifications %}
<ul id="notifications">
{% for notification in notifications %}<li class="{{ notification.type }}">{{ notification.content }}</li>
{% endfor %}
</ul>
{% endif %}`
[rendered example](http://traviscline.com/blog/2008/08/23/django-middleware-session-backed-messaging/)
based on Snippet [799](http://www.djangosnippets.org/snippets/799/) but added code inspection capabilities. Credit goes to django-logging for the actual inspection code.
Got the idea from the [This Week in Django](http://blog.michaeltrier.com/2008/6/18/this-week-in-django-26-2008-06-16) Podcast ;)
This adds the filename, lineno, functionname and the actual python-code line which caused a sql statement to be executed.
Note that i am adding keys to 'connection.queries' dict on request, which may be dangerous, so use with care!
The code inspection functionality can be toggled via FRAME_INSPECT.
**This is a newforms field for OpenID 1 & 2.**
It normalizes and validates OpenID identifiers according to the [spec](http://openid.net/specs/openid-authentication-2_0.html#normalization):
* `xri://=joelwatts` to `=joelwatts`
* `joelwatts.com` to `http://joelwatts.com/`
* `www.joelwatts.com` to `http://joelwatts.com/`
An identifier that is well-formed, but not an OpenID (e.g. `example.com`), will cause a validation error.
Requires [Python OpenID Library](http://openidenabled.com/python-openid/) 2.x.x.
The Django docs show us how to give models a custom manager. Unfortunately, filter methods defined this way cannot be chained to each other or to standard queryset filters. Try it:
class NewsManager(models.Manager):
def live(self):
return self.filter(state='published')
def interesting(self):
return self.filter(interesting=True)
>>> NewsManager().live().interesting()
AttributeError: '_QuerySet' object has no attribute 'interesting'
So, instead of adding our new filters to the custom manager, we add them to a custom queryset. But we still want to be able to access them as methods of the manager. We could add stub methods on the manager for each new filter, calling the corresponding method on the queryset - but that would be a blatant DRY violation. A custom `__getattr__` method on the manager takes care of that problem.
And now we can do:
>>> NewsManager().live().interesting()
[<NewsItem: ...>]
*Incredibly useful for storing just about anything in the database (provided it is Pickle-able, of course) when there isn't a 'proper' field for the job:*
A field which can store any pickleable object in the database. It is database-agnostic, and should work with any database backend you can throw at it.
Pass in any object and it will be automagically converted behind the scenes, and you never have to manually pickle or unpickle anything. Also works fine when querying.
**Please note that this is supposed to be two files, one fields.py and one tests.py (if you don't care about the unit tests, just use fields.py)**
A simple login form that does the actual authentification itself.
**Usage:**
if request.method == "POST":
loginform = LoginForm(request.POST)
if loginform.login():
return HttpResponseRedirect(redir_url)
else:
loginform = LoginForm()
This code works with Django-registration app found here: http://code.google.com/p/django-registration/
If you plan to use this django-registrtion code in your website to allow user registration but do not run your own email server,this snippet can be handy.
It uses gmail server to send out email.
You have to install libgmail module first.
Add two lines to your `settings.py`
GMAIL_USERNAME = '[email protected]'
GMAIL_PASSWORD = 'your_password'
Change models.py - create_inactive_user(...) as given above
This is the result of my first tests with jQuery and Django.
After entering a search term it gets search results using ajax and json. Then is uses the rather crude `result_table` function to generate a table of results.
Django is on the serverside for generating json
This is, I think, a slightly cleaner implentation of what [snippet 31](/snippets/31/) is trying to do; by starting off with a dictionary containing the things we want to look for, and using a list comprehension to kill anything which comes out of the form as `None`, we can avoid some of the intermediate data structures the other snippet was using, and hopefully get better performance.
This is also quite a bit more maintainable, because supporting additional options now only requires adding a new key/value pair to `qdict`.
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.