Login

All snippets written in Python

2956 snippets

Snippet List

truncatestring filter

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/.

  • filter
  • string
Read More

Hide Emails

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:&#106;&#x6f;&#x68;&#x6e;&#x40;&#101;&#120;&#97;&#109;&#x70;&#108;&#x65;&#46;&#x63;&#111;&#109;">&#74;&#111;&#104;&#110;&#x20;&#83;&#x6d;&#x69;&#x74;&#104;</a>') // ]]></script>

  • email
  • hide
  • protect
Read More

Reusable Logging

"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)

  • logging
Read More

DateTimeField with microseconds

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

  • forms
  • datetimefield
  • microseconds
Read More

Profanity Filter Middleware

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', )

  • middleware
  • profanity
Read More

SWFUpload auth decorator

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>`

  • authentication
  • decorator
  • auth
  • swfupload
  • login_required
Read More

No Password E-mail

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

  • middleware
  • password
  • exception
Read More

HTTP basic auth decorator

This is a somewhat simpler alternative to [http://www.djangosnippets.org/snippets/243/](http://www.djangosnippets.org/snippets/243/) that does not return a 401 response. It's meant to be used along with the login_required decorator as an alternative way to authenticate to REST-enabled views. Usage: @http_basic_auth @login_required def my_view(request): ... If an HTTP basic auth header is provided, the request will be authenticated before the login_required check happens. Otherwise, the normal redirect to login page occurs.

  • basic
  • authentication
  • decorator
  • auth
Read More

Unusable passwords for LDAP users

An example of how to modify the admin user creation form to assign an unusable password to externally authenticated users when they are created. This code is more intimate with the django.contrib.auth classes than I'd like, but it should be fairly straightforward to maintain should the relevant django.contrib.auth classes change.

  • admin
  • ldap
  • password
Read More

keywords arguments parser for custom template tags

returns a list of (argname, value) tuples (NB: keeps ordering and is easily turned into a dict). Params: * tagname : the name of calling tag (for error messages) * bits : sequence of tokens to parse as kw args * args_spec : (optional) dict of argname=>validator for kwargs, cf below * restrict : if True, only argnames in args_specs will be accepted If restrict=False and args_spec is None (default), this will just try to parse a sequence of key=val strings. About args_spec validators : * A validator can be either a callable, a regular expression or None. * If it's a callable, the callable must take the value as argument and return a (possibly different) value, which will become the final value for the argument. Any exception raised by the validator will be considered a rejection. * If it's a regexp, the value will be matched against it. A failure will be considered as a rejection. * Using None as validator only makes sense with the restrict flag set to True. This is useful when the only validation is on the argument name being expected.

  • template
  • tag
  • custom
  • template_tags
Read More

Formalchemy hack for newforms-based form validation

Very simple proof-of-concept that uses the django.forms library (newforms) for validation, and formalchemy for saving the model instance using sqlalchemy. it can be used like this (pseudo-code): if form.is_valid(): form.save(session=Session, app_label='Contact') Feel free to improve the concept. Ideally, either use formalchemy or django.forms but not both like this example. ;-)

  • newforms
  • hack
  • formalchemy
  • notmm
  • sqlalchemy
Read More

Complex Formsets

Background ========== Edit: This snippet doesn't make a lot of sense when Malcolm's blog is down. Read on for some history, or go [here](http://www.djangosnippets.org/snippets/1955/) to see the new trick that Malcolm taught me. A year ago, Malcolm Tredinnick put up an excellent post about doing complex Django forms [here](http://www.pointy-stick.com/blog/2008/01/06/django-tip-complex-forms/). I ended up reinventing that wheel, and then some, in an attempt to create a complex formset. I'm posting my (partial) solution here, in hopes that it will be useful to others. Edit: I should have known - just as soon as I post this, Malcolm comes back with a solution to the same problem, and with slightly cleaner code. Check out his complex formset post [here](http://www.pointy-stick.com/blog/2009/01/23/advanced-formset-usage-django/). I'll use Malcolm's example code, with as few changes as possible to use a formset. The models and form don't change, and the template is almost identical. Problem ======= In order to build a formset comprised of dynamic forms, you must build the forms outside the formset, add them, and then update the management form. If any data (say from request.POST) is then passed to the form, it will try to create forms inside the formset, breaking the dynamically created form. Code ==== To use this code: * Copy `BaseDynamicFormSet` into your forms.py * Create a derived class specific to your needs (`BaseQuizDynamicFormSet` in this example). * Override `__init__`, and keep a reference to your object that you need to build your custom formset (`quiz`, in this case). * Call the parent `__init__` * Call your custom add forms logic * Call the parent `_defered_init` To write your custom add_forms logic, remember these things: * You've got to pass any bound data to your forms, and you can find it in self.data. * You've got to construct your own unique prefixes by doing an enumerate, as shown in the example above. This is the same way it is usually handled by the formset. Add a `formset_factory` call, and specify your derived dynamic formset as the base formset - we now have a `QuizFormSet` class that can instantiated in our view. The view and template code look identical to a typical formset, and all of the dynamic code is encapsulated in your custom class. Warning ======= This solution does not yet handle forms that work with files, use the ordering/delete features, or adding additional forms to the set via javascript. I don't think that any of these would be that hard, but don't assume that they'll just work out of the box.

  • formset
Read More

Severity codes in user messages

This is the code for a template tag. Put this code in your template to render your messages: {% for message in messages %} {% render_user_message message %} {% endfor %} When you're adding a message to the user's message set, follow these rules: If you want a message to appear as an error, append "0001" to the end of it. To appear as a notice, append "0002" to it. To appear as a happy message, appear "0000" to it. If no code is present, it will default to displaying as an error. This makes use of the classes "error", "notice", and "success", so you need to define these in your CSS. For help with custom template tags, see [the Django docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)

  • user
  • message
Read More

Dynamic growing model

This model is designed for my webshop. The Client-object is very 'stretch-able' by defining more fields to the client. These extra fields ares stored in the ClientConfig-object. Be sure to create a new Client-instance first and SAVE it! Without a client.id the ClientConfig won't work.

  • django
  • dynamic
  • model
  • example
  • client
Read More