This method lets you define your markup language and then processes your entries and puts the HTML output in another field on your database.
I came from a content management system that worked like this and to me it makes sense. Your system doesn't have to process your entry every time it has to display it. You would just call the "*_html" field in your template.
Requires:
Django .96
[Markdown](http://cheeseshop.python.org/pypi/Markdown/1.6 "Python Package Index: Markdown")
[Textile](http://cheeseshop.python.org/pypi/textile "Python Package Index: Textile")
In response to [#366](/snippets/366/), this is a subclass of the `CommentModerator` class from `comment_utils` which does nothing except email the "owner" of an object whenever a new comment is posted on it; all other moderation options remain inactive.
I know ubernostrum has the nice comment_utils, but I need something that would notify the owner of the comment's content object (where the model has a foreignkey field to django.contrib.auth.models.User), but I didn't need all the moderation stuff. I stuck this in my models.py, where YOURMODEL is the name of the model object with comments attached, and a user field.
This snippet demonstrates how you can send a file (or file-like object) through Django without having to load the whole thing into memory. The FileWrapper will turn the file-like object into an iterator for chunks of 8KB.
This is a full working example. Start a new app, save this snippet as views.py, and add the views to your URLconf. The send_file view will serve the source code of this file as a plaintext document, and the send_zipfile view will generate a Zip file with 10 copies of it.
Use this solution for dynamic content only, or if you need password protection with Django's user accounts. Remember that you should serve static files directly through your web server, not through Django:
http://www.djangoproject.com/documentation/modpython/#serving-media-files
This handler is useful if you serve static/media files directly from Apache only to authenticated users. It checks if a user is not anonymous (and therefore logged in) and redirects to the login site if needed.
The following apache config activates the handler:
<Location "/site_media/company1">
#SetHandler None ##Uncomment if you serve static files in the same virtual host
PythonOption DJANGO_SETTINGS_MODULE mysite.settings
PythonAuthenHandler mysite.myhandler
PythonPath "['/path/to/project'] + sys.path"
Require valid-user
</Location>
Tag library that provides support for *macros* in Django templates.
**Usage example:**
**0)** Save this file as
<yourapp>/templatetags/macros.py
**1)** In your template load the library:
{% load macros %}
**2)** Define a new macro called 'my_macro' with parameter 'arg1':
{% macro my_macro arg1 %}
Parameter: {{ arg1 }}
{% endmacro %}`
**3a)** Use the macro with a String parameter:
{% usemacro my_macro "String parameter" %}
**3b)** or with a variable parameter (provided the context defines 'somearg' variable, e.g. with value "Variable parameter"):
{% usemacro my_macro somearg %}
**3c)** **!!NEW!!** `usemacro` now also supports filters attached to parameters:
{% usemacro my_macro "lowercase parameter"|upper %}
Output of the above code would be:
Parameter: String parameter
Parameter: Variable parameter
Parameter: LOWERCASE PARAMETER
**4)** **!!NEW!!** Alternatively save your macros in a separate file, e.g. "mymacros.html" and load it into the current template with:
{% loadmacros "mymacros.html" %}
Macros can take *zero or more arguments* and both context variables and macro arguments are resolved in macro body when used in `{% usemacro ... %}` tag.
Bear in mind that Macros are local to each template file and are not inherited through `{% extends ... %}` blocks.
This allows for urls in the form of `/grandparent-slug/parent-slug/self-slug/` where the number of parent slugs could be 0 to many.
You'll need to make sure that it is your last urlpattern because it is basically a catch-all that would supersede any other urlpatterns.
Assumes your page model has these two fields:
* `slug = models.SlugField(prepopulate_from=("title",), unique=True)`
* `parent = models.ForeignKey("self", blank=True, null=True)`
Often a page contains a link to itself, with an additional parameter for in the url.
E.g. to sort the page in a different way, to export the data into another format, etc...
This tag makes this easy, avoiding any hardcoded urls in your pages.
A variation on a theme, inspired by [snippet 39][39] and [snippet 119][119]. The
intent is to provide a more generic and simple mechanism for combining
[Markdown][markdown] with [Pygments][pygments]. Common scenarios could include blogging or commenting. Snippet 119 seemed too specific and perhaps not as
efficient, needing to process the HTML twice to accomplish it's ends. The one snag in the implementation is the need to use a tag other than `code` as a wrapper. See the comments for details.
You will need the [BeautifulSoup][soup] module installed.
Sample usage:
from django.db import models
class Blog(models.Model):
'''Bare bones blogging model'''
title = models.CharField(maxlength=255)
slug = models.SlugField(maxlength=255, prepopulate_from=('title',))
pub_date = models.DateTimeField()
# the cooked view, cached for quick retrieval
blog = models.TextField()
# the raw markdown-encoded text, saved for subsequent edits
markdown = models.TextField()
def save(self):
from datetime import datetime
if not self.id and not self.pub_date:
self.pub_date = datetime.now()
self.blog = pygmented_markdown(self.markdown)
super(Blog, self).save()
[39]: http://www.djangosnippets.org/snippets/39/
[119]: http://www.djangosnippets.org/snippets/119/
[soup]: http://www.crummy.com/software/BeautifulSoup/
[markdown]: http://www.freewisdom.org/projects/python-markdown/Installation
[pygments]: http://pygments.org/
The models in the Site Administration screen are listed alphabetically. If you need to order them differently, say, in the order of creation of objects or some other 'workflow' criterion, you can use the instructions in this snippet.
Use this to display a split of page execution time between python and the db in your base template when debugging.
I originally got the base of this code from another snippet, but I can't find it anymore and want to share with new folks because I find this handy.
A revised version of [zeeg's Sphinx Search ORM](http://www.djangosnippets.org/snippets/231/), using my Sphinx client and adding support for Sphinx's excerpt generator. It's still missing support for search modes/order_by/filter/exclude, but it should be easy and I will add the relevant methods soon as I need them.
Usage is the same as zeeg's class, except that you can pass a field name (or tuple for related objects) to its constructor, that will be used for excerpts:
class MyModel(models.Model):
search = SphinxSearch(excerpts_field='description')
MyModel.search.query('query')
MyModel.search.query('query').count()
Returns an ordered list of the objects in your database.
Python's [descriptor][1] protocol can seem a bit esoteric at first; however, it can
be invaluable in handling everyday idioms and patterns - something that the
Django framework authors have taken advantage of in numerous occasions
(e.g.: [auth middleware][2]).
One such idiom I see and use often and would like to generalize is the
attribute-existence check-or-set routine illustrated here:
def get_foo(self):
if not hasattr(self, '_foo'):
self._foo = init_foo()
return self._foo
Rather than coding this up multiple times (either for a given class or across
many unrelated classes), I would prefer to delegate this repetitive work to a
descriptor and remain [DRY][3]. The means to this end is implemented as a
variation on the Python `property` construct, and is intentionally over simplistic
(I leave the details of the heavy lifting up to the reader).
The basic premise shown in source here is simply straight-forward Python, a
quick and dirty example of how it could be utilized within a Django context is
shown here:
from django.db import models
from cacheprop import CacheProperty2
ARTIFACT_TYPES = (
('F', _('File')),
('D', _('Directory')),
('A', _('Alias')),
)
class Artifact(models.Model):
# model fields
name = models.CharField(maxlength=64)
type = models.CharField(maxlength=1, choices=ARTIFACT_TYPES)
file_metadata = CacheProperty2(
lambda self: self.filemetadata_set.get(artifact__id=self.id)
)
class FileMetadata(models.Model):
byte_size = models.IntegerField()
artifact = models.ForeignKey(Artifact, unique=True)
[1]: http://users.rcn.com/python/download/Descriptor.htm
[2]: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/middleware.py
[3]: http://c2.com/cgi/wiki?DontRepeatYourself
This is a special URL patterns replacement that prevents caching of any URL listed within it. We needed this in Review Board to prevent the JSON API function results from being cached in Internet Explorer.