Login

All snippets

Snippet List

A small script to rearranging the models generated from inspectdb command

`python manage.py inspectdb` allows you to generate the models from a legacy database. The generated model classes are not arranged by dependencies. When the number of tables is big, it becomes really painful to rearrange by hand. This small script should rearrange the models for you. It doesn't solve every problem with generated models, but it makes our the process easier

  • admin
  • inspectdb
  • arrangement
Read More

SelectTimeWidget

This snippet defines a Widget that is very similar to the **SelectDateWidget** located in django.forms.extras.widgets. The main difference however is that it works with Times instead of Dates. The SelectTimeWidget supports both 24-hr and 12-hr formats, and flexible time increments for hours, minutes and seconds. Sample usage is illustrated below: # Specify a basic 24-hr time Widget (the default) t = forms.TimeField(widget=SelectTimeWidget()) # Force minutes and seconds to be displayed in increments of 10 t = forms.TimeField(widget=SelectTimeWidget(minute_step=10, second_step=10)) # Use a 12-hr time format, which will display a 4th select # element containing a.m. and p.m. options) t = forms.TimeField(widget=SelectTimeWidget(twelve_hr=True))

  • forms
  • widgets
Read More

Integrate Wymeditor with filebrowser plugin

In order to integrate Wymeditor with the Django filebrowser, put the code in a file, set the fb_url variable to point to your filebrowser instance and add the file to your Javascript headers: <script type="text/javascript" src="/media/wymeditor/plugins/jquery.wymeditor.filebrowser.js"></script> or in your admin.py: class Media: js = ('/media/wymeditor/plugins/jquery.wymeditor.filebrowser.js',) Add the postInitDialog parameter to the Wymeditor initialization: $('textarea').wymeditor({ postInitDialog: wymeditor_filebrowser }); If you already have a postInitDialog function, you need to put a call to wymeditor_filebrowser inside that function. Then you should be able to click on the Filebrowser link to select an image.

  • javascript
  • images
  • wymeditor
  • filebrowser
Read More

Multiple Choice model field

Usually you want to store multiple choices as a manytomany link to another table. Sometimes however it is useful to store them in the model itself. This field implements a model field and an accompanying formfield to store multiple choices as a comma-separated list of values, using the normal CHOICES attribute. You'll need to set maxlength long enough to cope with the maximum number of choices, plus a comma for each. The normal get_FOO_display() method returns a comma-delimited string of the expanded values of the selected choices. The formfield takes an optional max_choices parameter to validate a maximum number of choices.

  • multiple
  • model
  • form
Read More

Use MEDIA_URL in 500 error page

The default server_error view uses Context instead of RequestContext. If you were depending on a context processor to make MEDIA_URL available in your templates, your 500.html template will not render with the correct image paths. This handler adds MEDIA_URL (and nothing else) back to the context that is sent to the template.

  • media
  • 500
  • handler
  • servererror
Read More

Simple E-mail registration

This is a simplified rip-off of django-registration and the built-in forms and views in contrib.auth. It requires no models and is very customizable. Saving the form creates a user with an unusable password and sends a password reset email (by default, uses the password reset template too). You must create templates/registration_form.html and the view registration_complete. I ripped this out of my site, which has a more complicated form, so I may be missing a few other things here.

  • registration
  • email
Read More

Add site info to request context

Sometimes you want to generate a **really** absolute URL, but the built-in url tag only generates a URL relative to the current domain. This context processor adds the extra information needed to the request context, so you can generate an absolute URL in a template like so: `{{ protocol }}://{{ domain }}{% url someview %}` This is similar to how the password reset email from contrib.auth generates the full URL in the email. Save this somewhere as context_processors.py (or add to existing file if you have one), and add context_processors.site to your TEMPLATE_CONTEXT_PROCESSORS setting.

  • contextprocessor
  • domain
  • site
Read More

Username form field

Use a `UserField` if you want to replace the usual select menu with a simple input field that only accepts valid user names. Should be easy to generalize for other models by passing a query set and the attribute name that represents the instance. Example: class Book(models.Model): owner = models.ForeignKey(User) class BookForm(forms.ModelForm): owner = UserField() class Meta: model = Book

  • user
  • form
  • field
  • username
  • textual
Read More
Author: sma
  • 1
  • 2

FixedCharField and related

FixedCharField is used similarly to CharField, but takes a length attribute, and will only accept strings with that exact length. class Student(models.Model): student_id = FixedCharField(length=8) It currently only supports mysql, sqlite3, and oracle. The port to postgresql should be straightforward but I'm not sure about it so I haven't added it yet. This is a copy-paste (plus a couple of adaptations) from my project Chango, found at http://launchpad.net/chango/, so in order to keep up with latest updates it might be a good idea to use code directly from there.

  • field
  • form-field
  • fixed-length
Read More

iPernity thumbnail helper

A simple template filter that detects [iPernity](http://www.ipernity.com) static URLs and creates clickable thumbnail for them. Use it with [Lightbox](http://www.huddletogether.com/projects/lightbox2/) or any other funky image overlay script. Your HTML code may contain this: <p>A short example <img src="http://...ipernity..." title="The Description" />.</p> After applying this filter it will become: <p>A short example <a href="http://...large version..." title="The Title"><img alt="The Title" src="http://...thumb version..."/> </a>.</p> Thats all! You may have a look at this: [iPernity and static URLs](http://www.ipernity.com/group/api-users/discuss/20098)

  • template
  • image
  • thumbnail
  • resize
  • ipernity
Read More

Using another memcached for sessions

This solves the problem of losing sessions data when you restart memcached. So you use a different memcached instance for sessions which you rarely restart. Use the above code and add the following to you settings.py SESSION_ENGINE = "kwippyproject.session_backend" SESSION_CACHE = 'memcached://127.0.0.1:11200/' (Above assumes that your session's memcached is running on port 11200) Feel free to contact me in case you need help. By [Dipankar sarkar](http://dipankar.name) [email protected]

  • django
  • python
  • memcached
  • sessions
Read More

Cheap direct_to_tempalte patterns

Django cheap-pages Methods to use when you just want to use the Django dispatcher and there will be no extra business logic in your pages. In some cases flatpages is too flat, and store templates in DB is too much hassle >>> url(^name/$, ... direct_to_template, ... {'template': 'name.html'}, ... name='name') can be expressed as: >>> page('name') urlpatterns = patterns('', ...) urlpatterns += build('Regexp', ['page1', 'page2', ...])

  • generic
  • urlpatterns
  • direct_to_template
Read More

A form field for valdating PDF and Microsoft Word document

This is form field for PDF or Microsoft Word Document (both .doc and .docx) It will validate the file uploaded as a valid PDF and MS Word Document. It extends a forms.FileField, so you can put all the arguments relevant to FileField. IMPORTANT NOTE: The method of validation is actually run thru *nix OS shell command 'file', therefore, 1. only *nix system can use this class. 2. The file uploaded must be saved on disk, meaning you need to set your upload handler to use TempoaryFileUploadHandler Only. # (i.e. put this in your settings.py) FILE_UPLOAD_HANDLERS = ( "django.core.files.uploadhandler.TemporaryFileUploadHandler", )

  • pdf
  • microsoft-word-document
  • form-field
Read More

3110 snippets posted so far.