Login

All snippets

Snippet List

Natural language date/time form fields

Form fields use the dateutil module [http://labix.org/python-dateutil](http://labix.org/python-dateutil) to parse natural-language input for date and datetime fields. The callback function will replace all date and datetime fields automatically for form_for_model and form_for_instance. **Note**: by replacing the 'form_class' keyword argument instead of just returning the field itself you preserve the 'required' status of the field.

  • newforms
  • datetime
  • date
Read More

browscap.ini-parser

Sometimes you need to know if a visitor is a bot or if the browser supports certain features or if it is a mobile device. The easiest way to do so would be to lookup the user agent in a capabilities database. Fortunately there is already such a database called browscap.ini which is widely known among PHP users. I found the file accidently on my harddrive because it is also used by Mono: /etc/mono/browscap.ini Read http://browsers.garykeith.com/index.asp for more information. Before importing the module you need to call the script from commandline to retrieve the browscap.ini file. Look at the test function to see how to use it. You can also create a file called "bupdate.ini" which can contain fixes for wrong or incomplete entries, e.g: [Konqueror] javaapplets=True

  • ie
  • browscap
  • browser
  • detection
  • firefox
  • opera
  • mozilla
  • safari
Read More

assigning many partially deviant variables

This was a much better way of incrementing variables that only changed a small amount in name. deltab in #python also said I could have used tuples, but I'm not familiar with them yet, so I added this to a list of things to look into.

  • assignment
  • variable
  • for-loop
Read More

email_links

A very basic app centered around a template tag that takes an e-mail address and optional label and returns a link to an e-mail form. This way, you can easily throw e-mail addresses into your template that will automatically link to an e-mail form instead of displaying the e-mail address itself. The model for this app is extremely simple, with only one field to store the e-mail address. When an e-mail is passed to the email_link template tag, the e-mail address is added to the database if it is not already there. This is stored in the database in order to keep the full e-mail address hidden from the viewer. To use, simply create an app called 'email_links' (or you can change the name if you also change line 4 of email_extras.py to reflect the change). Then use the models.py and views.py provided. Add a templatetags directory under your app, and add email_extras.py and a blank __init__.py In your urls.py, add the following to your urlpatterns (subsitute project_name for your own): `(r'^email/(?P<email_id>[0-9]+)/$', 'project_name.email_links.views.email_form'),` Create two templates: email_links/email_form.html and email_links/thanks.html (the examples here are extremely basic - make them however you want). Finally, in a template where you want to provide a link to e-mail someone, first load email_extras: `{% load email_extras %}` Then do one of the following: `{% email_link "[email protected]" %}` `{% email_link "[email protected]" "E-mail someone" %}` Both will create a link to the e-mail form. The first will use mask_email (from the snippet by jkocherhans) to create the link. The second will display the second argument "E-mail someone" in the link. Also note that I've used the Sites add-on to generate the links, but you can easily change this to suit your needs. I hope all of this makes sense. I'm a bit tired, but wanted to get this up before bed.

  • filter
  • tag
  • email
Read More

TerminalLoggingMiddleware

A handy ANSI-colored logging mechanism to display the SQL queries and times in the terminal when using django-admin.py runserver. DEBUG mode must be true for this to work.

  • sql
  • middleware
  • terminal
  • logging
Read More

Form rendering using a template instead of builtin HTML

As an alternative to using forms rendered with the default hard-coded html, this factory function will take a template name as argument, and return a Form class based on django.newforms.BaseForm, which will render each form field using the supplied template. As an example, I'm using this class as follows in one project (slightly edited with respect to project and app names): # Get a form class which renders fields using a given template CustomForm = proj.utils.makeTemplatedForm(template="app/formfield.html") # Get base form class for the details model BaseAppForm = forms.form_for_model(models.AppDetail, form=CustomForm) using this template: {% if errors %} <ul class="errorlist"> {% for error in errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} {% if field.required %}<span class="required">*</span>{% endif %}{{ text }} {{ help_text }}

  • template
  • newforms
  • rendering
Read More

Changing the look of newforms as_table with a custom BaseForm

I wanted to mark rows with an erroneous input with 'class="error"' and move the errorlist below the input tag so I wrote a NormalRowFormatter which behaves like a format string by overwriting \_\_mod\_\_. Examples: class MyForm(PrettyBaseForm, forms.Form): # add your fields here SomethingForm = form_for_model(Something, form=PrettyBaseForm)

  • newforms
  • error
  • baseform
  • as_table
  • pretty
  • prettybaseform
  • _html_output
  • style
Read More

Simple Contact Form

Simple contact form, using a javascript form checker which you can use any you want to you can just modify the form in the way you want to. The form checker I use I include in the 'base.html' page before the </head> section end. You can use it freely. http://media.xorl.de/form.js . A lot of this code is comprised of other peoples forms that didn't suit the simple purpose of a *really* basic contact form which I wanted, so I rebuilt it up from bits and pieces to make a simple basic form.

  • python
  • form
  • contact
Read More

Add validation for 'unique' and 'unique_together' constraints to newforms created dynamically via form_for_model or form_for_instance

This snippet provides a form_for_model and form_for_instance function which create newforms that respect the unique and unique_together constraints defined in the model. One thing about the coding style in this code snippet: Classes are capitalized even if they're passed as arguments. Thus "Model" is a model class while "model" is a model instance.

  • newforms
  • form_for_model
  • form_for_instance
  • unique_together
  • unique
  • formfield_factory
Read More

Ordered items in the database - alternative

Every now and then you need to have items in your database which have a specific order. As SQL does not save rows in any order, you need to take care about this for yourself. No - actually, you don't need to anymore. You can just use this file - it is designed as kind-of plug-in for the Django ORM. Usage is (due to use of meta-classes) quite simple. It is recommended to save this snippet into a separate file called `positional.py`. To use it, you only have to import `PositionalSortMixIn` from the `positional` module and inherit from it in your own, custom model (but *before* you inherit from `models.Model`, the order counts). Usage example: Add this to your `models.py` from positional import PositionalSortMixIn class MyModel(PositionalSortMixIn, models.Model): name = models.CharField(maxlength=200, unique=True) Now you need to create the database tables: `PositionalSortMixIn` will automatically add a `postition` field to your model. In your views you can use it simply with `MyModel.objects.all().order_by('position')` and you get the objects sorted by their position. Of course you can move the objects down and up, by using `move_up()`, `move_down()` etc. In case you feel you have seen this code somewhere - right, this snippet is a modified version of [snippet #245](/snippets/245/) which I made earlier. It is basically the same code but uses another approach to display the data in an ordered way. Instead of overriding the `Manager` it adds the `position` field to `Meta.ordering`. Of course, all of this is done automatically, you only need to use `YourItem.objects.all()` to get the items in an ordered way. Update: Now you can call your custom managers `object` as long as the default manager (the one that is defined first) still returns all objects. This Mix-in absolutely needs to be able to access all elements saved. In case you find any errors just write a comment, updated versions are published here from time to time as new bugs are found and fixed.

  • db
  • orm
  • database
  • plugin
  • mixin
Read More

run "silent" dev server

This will hide the scrolling output from the development server so you can ssh and run the server in peace, for those of us with only one SSH session active developing on a remote server.

  • bash
  • runserver
  • daemon
Read More

Left Outer join Q object

QLeftOuterJoin object allows you to create 'LEFT OUTER JOIN' sql query. It is very usefull if you have to define ForeignKey to 'null=True' (select_related will not work with null=True). You are allowed to use QLeftOuterJoin like Q object. Example: `QLeftOuterJoin('thread_last_post', Post, 'pk', Thread, 'last_post')` It will generates SQL like: LEFT OUTER JOIN appname_post AS thread_last_post ON thread_last_post.id = appname_thread.last_post_id Table could be model or string.

  • sql
  • q
  • query
  • join
Read More

Add delete buttons to admin changelist

This adds a checkbox for each object and three buttons to a model's change list: 1. **Delete selected:** deletes the selected objects 2. **Delete shown: ** deletes all the visible objects. For example, if you perform a search or in any way filter the list, this button deletes only objects that were filtered. 3. **Delete all: ** Deletes all instances of the model, including those not shown (if looking at a filtered list). The deletes perform no confirmation -- once you hit the buttons the models are **gone**, so maybe don't use (or add a confirmation screen) for really sensitive stuff. * uses django oldforms-admin (ie 0.96) * works fine if you include a search_fields list in the Admin class * code for the view could probably be refactored a bit :)

  • admin
Read More

Auth decorators with 403

These decorators are based on user_passes_test and permission_required, but when a user is logged in and fails the test, it will render a 403 error instead of redirecting to login - only anonymous users will be asked to login.

  • auth
  • user_passes_test
  • 403
  • permission_required
Read More

3110 snippets posted so far.