A few jinja2 filters like django ones
Some of this is modified from [http://www.djangosnippets.org/snippets/1062/](http://www.djangosnippets.org/snippets/1062/)
- filters
- template-filters
- jinja2
Some of this is modified from [http://www.djangosnippets.org/snippets/1062/](http://www.djangosnippets.org/snippets/1062/)
This is heavily inspired by [http://code.google.com/p/smorgasbord/](http://code.google.com/p/smorgasbord/). But that couldn't reuse an existing jinja2 Environment, nor set filters on the Environment it created. This code assumes that you have `env` declared previously in the file as your Jinja2 Environment instance. In `settings.py`, you should set KEEP_DJANGO_TEMPLATES = ( '/django/contrib/', ) so that your Django admin still works. You can also set any other places that you do want to use Django templates there.
Middleware for implementing "hours of operation" for a website. In use (as configured here) on http://ianab.com/.
There are probably ways to improve the implementation, but this was something I came up with when I wanted to change the default size of all of my CharField admin fields. Now all I have to do in my ModelAdmin class is: form = get_admin_form(model) or subclass BaseAdminForm if I need extra validation or more widget customization for an individual admin form.
http://steven.bitsetters.com/articles/2009/03/09/testing-email-registration-flows-in-django/ Testing email registration flows is typically a pain. Most of the time I just want to sign up with a test user, get the email link and finish the flow. I also want to be able to automate the whole process without having to write some SMTP code to check some mail box for the email. The best way I’ve found to do this is just to write out your emails to some file instead of actually sending them via SMTP when your testing. Below is some code to do just that. I’ve also created a Django management script that will open the last email sent out from your application, find the first link in it and open it in your web browser. Quite handy for following email registration links without logging into your email and clicking on them manually.
This snippet is working code, however it is not intended for proper use, rather to garner comment on an alternative style of view - using a class for views, rather than a function. While working with views, I've often felt that the traditional django code layout splits concerns in an unnatural fashion. The parameters for a view must be maintained in both the urls file as well as the view for example, and there is no neat way of grouping multiple accessor for a REST resource. This 'shim' code aims to propose an alternative architecture, that is interchangeable with the existing system. Rather than include a tuple of urls, instead a list of classes is provided. Each class models a resource, or page. Page objects have a url property and name property, so it is therefor trivial to reconstruct the url tuple from the class, but allow more simplicity and structure in relating the methods of the resource. You may notice that this structure closely follows the architecture of the web.py framework - this syntax did indeed play a part in the concept for such a structure. While this paradigm may not be suitable in all situations, I believe it promotes a simpler, more encapsulated views architecture. Any comments and feedback are welcomed. Example usage (untested, sorry): class Homepage(Page): def get(request): return HttpResponse("Hello World") urlpatterns = patterns('', Homepage, url('^existing$', existing.view.function, name = "foo"), )
Simple filter that truncates string to specific number of letters. Example usage in template: `{{ myvariable|truncatestring:20 }}` if myvariable is "That is my long string", the result will be: "That is my long s...". Put the code into templatetags/.
Example Usage in the template: <p>{{ email|hide_email }}<br /> {{ email|hide_email:"Contact Me" }}<br /> {% hide_email "[email protected]" %}<br /> {% hide_email "[email protected]" "John Smith" %}</p> {{ text_block|hide_all_emails|safe }} All hidden emails are rendered as a hyperlink that is protected by javascript and an email and name that are encoded randomly using a hex digit or a decimal digit for each character. Example of how a protected email is rendered: <noscript>(Javascript must be enabled to see this e-mail address)</noscript> <script type="text/javascript">// <![CDATA[ document.write('<a href="mai'+'lto:john@example.com">John Smith</a>') // ]]></script>
"Thus, if a LOGGER is configured inside settings.py, we use that. Otherwise, we just use vanilla logging functions with the global logging configuration. Nice and sweet." Naturally, the logger can be anything described [here](http://docs.python.org/library/logging.html), I'm just using the RotatingFileHandler as an example because that's what I was using in my project. Full write up+shamless plug [here](http://mihasya.com/blog/?p=237)
Use this in your form if you want to accept input in microseconds. In a ModelForm you can override the field like this: def __init__(self, *arg, **kwargs): super(MyForm, self).__init__(*arg, **kwargs) self.fields['date'] = DateTimeWithUsecsField() *Update* May 26 2009 - Updated to address a couple issues with this approach. See http://code.djangoproject.com/ticket/9459
I wanted a global way to filter profanity w/out having to modify every model, view, or form. While middleware takes overhead, this technique is intended mainly for sites w/few postbacks. Hopefully this snippet will lead to more/better techniques in the comments below. Usage (settings.py): MIDDLEWARE_CLASSES = ( 'PROJECT_NAME.FILE_NAME.ProfanityFilterMiddleware', )
I ended up not needing this (there's a good reason it's in JS and not Python, but most people would probably want to do this server-side instead) but I'm stashing it here in case I need it later. It uses jQuery for the .each() method - which is very easy to replace if you need it to work without that dependency. Usage: var src = generateChart({ "foo": 5, "bar": 3, "baz": 6 });
I use this snippet to simplify my auth system with flash uploader SWFUpload. flash_login_required ensures that the user is authenticated and inject the context dictionnary into the specified template. To redirect a user, just set the variable `context['redirect']` with an url. Remember to include the cookie js in your template to get the sessionid variable POSTed to your view: `<script type="text/javascript" src="/static/js/swfupload/swfupload.cookies.js"></script>`
Sometimes when a Django site's authentication backend goes down, a login will fail with a 500 error. This has happened to me when using an LDAP backend for authentication. A glitch with the settings, or ldap temporarily disappearing can make logins flake out for a short period of time. That's fine, but when a 500 error occurs it e-mails detailed information about the error to the ADMINS. We like this behavior for most errors, but it is quite frustrating when it is a login form with a password as part of a POST. If it is one of us who gets our password e-mailed out, it's even more frustrating. It hits a mailing list first, and goes to the archives to be stored in plain text. It goes to several e-mail inboxes, some of which are not local inboxes. I decided that enough was enough. Drop this middleware in, and it will change a "password" field in the POST to twenty asterisks. This was the default way to display other sensitive settings on the DEBUG page, so I figured I'd be consistant with that. This snippet is distributed under the GPLv3 License http://www.gnu.org/licenses/gpl-3.0-standalone.html
Django tagging by default doesn't provide a templatetag to get the related objects for another object. Even though this is implemented as a model. Still, one can use the existing templatetags to achieve the same outcome. Of course, writing a custom templatetag would be more efficient in terms of database access.
3110 snippets posted so far.