Login

Most bookmarked snippets

Snippet List

Get admin url for a model

Add this to your model to be able to get their admin change link from anywhere Useful if you want to jump to the admin screen of an object you are looking at on the front end

  • admin
  • url
Read More

Nice form errors

Nicely output all form errors in one block, using field labels rather than the field attribute names.

  • forms
  • template-filter
  • errors
Read More

WebFaction fixes middleware

On WebFaction, each host has it's own Apache instance, with WebFaction's main Apache instance forwarding requests. This is very useful but means that some of the original information is lost. This middleware should be installed at the top of your list to restore this lost info. It includes the functionality that used to be in SetRemoteAddrFromForwardedFor before it was removed from Django.

  • middleware
  • ssl
  • webfaction
  • https
Read More

Google Analytics Template Tag

Includes the Javascript for Google Analytics. Will not show Google Analytics code when DEBUG is on or to staff users. Use {% googleanalyticsjs %} in your templates. You must set something like GOOGLE_ANALYTICS_CODE = "UA-1234567-1" in your settings file. Assumes 'user' in your template variables is request.user, which it will be if you use: return render_to_response('template.html',{ }, context_instance=RequestContext(request)) (Assuming django.core.context_processors.auth is in TEMPLATE_CONTEXT_PROCESSORS, which it is by default)

  • google
  • urchin
  • analytics
Read More

More information about users and groups in user admin

Based on [this snippet](http://www.djangosnippets.org/snippets/876/). More clean, with links to the related admin forms. Nice example on customization of contributed django admin apps. It adds the following to the user list interface: fields for is_superuser and is_staff, last login time; by default, short names of groups user is in (mousehover to see full names) It adds the following to the to group list interface: list of users in your groups. To enable, just put it somewhere and import it from your main urls.py: import utils/admin_auth.py

  • admin
  • customization
  • users
  • groups
  • roles
Read More

ImageField for admin with thumbnail

AdminImageWidget is a ImageField Widget for admin that shows a thumbnail. Usage example on a form: class IconForm(forms.ModelForm): icon = forms.ImageField(label='icon', widget=AdminImageWidget)

  • image
  • admin
  • thumbnail
  • imagefield
  • widget
  • imagewidget
Read More

LoginAsForm - Login as any User without a password

Sometimes the only way to reproduce a bug on a production site is to login as the User who encountered it. This form allows you to login as any user on the site. **Usage** @staff_member_required def login_as(request, template="login_as.html"): data = request.POST or None form = LoginAsForm(data, request=request) if form.is_valid() form.save() return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) ...

  • forms
  • login
  • auth
  • authenticate
  • form
  • auth.contrib
Read More

Template tag "ifregex" and "ifnotregex"

Outputs the contents of the block if the second argument matches (or not, depending on the tag) the regular expression represented by the first argument. Usage: {% ifregex "^/comments/" request.path %} ... {% endifregex %} {% ifnotregex "^/comments/" request.path %} ... {% else %} ... {% endifnotregex %}

  • template
  • templatetag
  • regex
  • ifregex
Read More

JSONField

This is a custom field that lets you easily store JSON data in one of your model fields. This is updated to work with Django 1.1. **Example: (models.py)** from django.db import models import JSONField class MyModel(models.Model): info = JSONField() ** Example: (shell)** >>> obj = MyModel.objects.all()[0] >>> type(obj.info) <type 'NoneType'> >>> obj.info = {"test": [1, 2, 3]} >>> obj.save() **[Code at GitHub](http://github.com/bradjasper/django-jsonfield/tree/master)**

  • models
  • fields
  • model
  • json
  • db
  • field
  • json-field
  • jsonfield
Read More

render_as_template template tag

This is a template tag that works like `{% include %}`, but instead of loading a template from a file, it uses some text from the current context, and renders that as though it were itself a template. This means, amongst other things, that you can use template tags and filters in database fields. For example, instead of: `{{ flatpage.content }}` you could use: `{% render_as_template flatpage.content %}` Then you can use template tags (such as `{% url showprofile user.id %}`) in flat pages, stored in the database. The template is rendered with the current context. Warning - only allow trusted users to edit content that gets rendered with this tag.

  • template
  • tag
  • context
Read More

Create short URL redirects for site urls.

This allows you to host your own URL shortening service for your site's internal urls. By adding this class as a Mixin to your models, any model with a get_absolute_url method will have a get_short_url method also, which either returns an existing redirect or creates a new one and returns that. **Usage:** Import the class above, add the mixin to your model declaration, and ensure you have declared a get_absolute_url method. `class MyModel = (models.Model, ShortURL):` **Pre-requisites:** You must have the django.contrib.redirects app installed, and you must be using the RedirectFallbackMiddleware as a middleware class. **Settings:** Change the settings in the code above or set them in your settings.py file SHORTURL_CHARS: the characters to use when creating a shorturl SHORTURL_CHAR_NO = the number of characters to use in a shorturl SHORTURL_APPEND_SLASH = whether to append a slash to the end of the shorturl redirect **Notes:** The default settings will give you about 17 million different unique short URLs, reducing the number of characters used to 4 will give you 600,000 or so. That's enough that collisions will be quite rare for sites of a few thousand pages (collisions just result in a urls being generated until an unused combination is found) but if you've got a big site you'll probably want to explore a more robust solution with a proper hash function. [http://matt.geek.nz/blog/text/generating-short-urls-django-site-urls/](http://matt.geek.nz/blog/text/generating-short-urls-django-site-urls/)

  • url
  • redirect
  • tinyurl
  • short
Read More

BetterForm with fieldsets and row_attrs

**NOTE**: Further development of this snippet will take place in the [django-form-utils](http://launchpad.net/django-form-utils) project. This snippet provides BetterForm and BetterModelForm classes which are subclasses of django.forms.Form and django.forms.ModelForm, respectively. BetterForm and BetterModelForm allow subdivision of forms into fieldsets which are iterable from a template, and also allow definition of row_attrs which can be accessed from the template to apply attributes to the surrounding container of a specific form field. It's frequently said that a generic form layout template is a pipe dream and in "real usage" it's necessary to manually layout forms, but in my experience the addition of fieldsets and row_attrs, plus a competent CSS designer, make it possible to create a generic template that can render useful production form markup in 95+% of cases. Usage: class MyForm(BetterForm): one = forms.CharField() two = forms.CharField() three = forms.CharField() class Meta: fieldsets = (('main', {'fields': ('two',), 'legend': ''}), ('Advanced', {'fields': ('three', 'one'), 'description': 'advanced stuff'})) row_attrs = {'one': {'style': 'display: none'}} Then in the template: {% if form.non_field_errors %}{{ form.non_field_errors }}{% endif %} {% for fieldset in form.fieldsets %} <fieldset class="fieldset_{{ fieldset.name }}"> {% if fieldset.legend %} <legend>{{ fieldset.legend }}</legend> {% endif %} {% if fieldset.description %} <p class="description">{{ fieldset.description }}</p> {% endif %} <ul> {% for field in fieldset %} {% if field.is_hidden %} {{ field }} {% else %} <li{{ field.row_attrs }}> {{ field.errors }} {{ field.label_tag }} {{ field }} </li> {% endif %} {% endfor %} </ul> </fieldset> {% endfor %}

  • fieldset
  • form
  • layout
Read More

3110 snippets posted so far.