Login

All snippets written in Python

Snippet List

orm_tools

This module contains classes that add new behavior to Django's ORM. Classes include: **Session** * Forces QuerySet objects to return identical instances when objects with the same primary key are queried. * Similar to [SQLAlchemy Session](http://www.sqlalchemy.org/docs/orm/session.html) **GraphSaver** * Save entire object graphs at once. * Automatically detects object dependencies and saves them in the correct order. **Collection** * Easier one-to-many relationships. Instructions and more information on [limscoder.com](http://www.limscoder.com/2011/01/django-orm-tools.html).

  • session
  • db
  • orm
Read More

path.py FilePathField

A slightly adapted FilePathField that converts path.py (http://pypi.python.org/pypi/path.py) objects into strings and back from the database.

  • custom field
  • filepathfield
  • path.py
Read More

Modifying the fields of a third/existing model class

You can extend the class **ModifiedModel** to set new fields, replace existing or exclude any fields from a model class without patch or change the original code. **my_app/models.py** from django.db import models class CustomerType(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Customer(models.Model): name = models.CharField(max_length=50) type = models.ForeignKey('CustomerType') is_active = models.BooleanField(default=True, blank=True) employer = models.CharField(max_length=100) def __unicode__(self): return self.name **another_app/models.py** from django.db import models from django.contrib.auth.models import User from this_snippet import ModifiedModel class City(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class HelperCustomerType(ModifiedModel): class Meta: model = 'my_app.CustomerType' description = models.TextField() class HelperCustomer(ModifiedModel): class Meta: model = 'my_app.Customer' exclude = ('employer',) type = models.CharField(max_length=50) # Replaced address = models.CharField(max_length=100) city = models.ForeignKey(City) def __unicode__(self): return '%s - %s'%(self.pk, self.name) class HelperUser(ModifiedModel): class Meta: model = User website = models.URLField(blank=True, verify_exists=False)

  • fields
  • model
  • helper
  • change
Read More

model instance to sql insert statement

This function will take a model instance and return an insert statement for it. I use it for extracting a subset of my production data so that I can reproduce problems in a local environment. The quoting is for mysql, you may have to change it depending on your db backend. Also, it assumes the 'default' database.

  • sql
  • model
  • db
Read More

cleat_list

Clear list from unwanted elements, within django template.

  • template
  • filter
  • list
  • clear
Read More

View to retrieve objects meeting a complex tag query

This view parses complex tag queries. It generates a list of model instances matching an expression of tags. The expression currently supports intersection, union and subtraction. Expressions can also be put in parenthesis and then combined with other expressions. The expression must be passed to this view in the tag_expression argument. In my application this is simply passed from the URL querystring. This snippet uses the django-tagging app. It assumes that tags are composed of alphanumeric characters, underscores, hyphens and spaces, but the django-tagging application allows tags with other characters, so you might either want to restrict users to using tags that only contain the above characters, or you might prefer to improve this snippet. Example: This URL http://example.com/people/?(deceased&parrot)|"Monty Python" will retrieve all people who are either deceased parrots or members of Monty Python. In the tag_expression argument: * ALL is treated as a keyword. If you happen (by some sad chance) to have a tag called ALL and want to use it in the expression, surround it in quotation marks. E.g. "ALL" * Examples: - famous -returns all instances of the model tagged with famous - famous&deceased -returns all instances of the model tagged both famous and deceased. - famous|deceased -returns all instances of the model tagged famous or deceased. - parrot-deceased -returns all alive parrots in the model. - ALL-deceased -returns all instances of the model that are not tagged deceased. - ALL -returns all instances of the model - "ALL" -returns all instances of the model that are tagged ALL - "great author"&deceased -returns all models tagged as great authors and deceased. Arguments: * request -- HTTP Request object * tag_expression -- a set expression of tags, supporting intersection, union, parenthesis and difference * app_name -- App for the model we're working on (defaults to pubman) * model_name -- Model on which to apply the set operations (defaults to Article) * view -- view to redirect to after the model instance list has been constructed * html_template -- HTML template to redirect (defaults to 'pubman/tag.html')

  • view
  • django-tagging
  • tag expression
Read More

Expose filtered settings to templates request context

**Warning**: I'm quite sure this is **not** a best practice, but this snippet has proven being very useful to me. Handle with care. I also wonder about the impact on performance, while I didn't notice any slowdown on a very small app of mine. Idea is to expose project settings to template request context through a context processor, and \__doc__ should be self-explanatory. Of course, if you know a better way to achieve the purpose, please tell in the comments.

  • templates
  • settings
  • python
  • context_processor
Read More

ReCaptcha for django forms (improved and with remoteip)

My previous snippet with captcha wasn't very portable but Marco Fucci figured out the thing that I couldn't - value_from_datadict function. So all credits go to him and his snippet, I adapted it to my needs, maybe you like my version better - it doesn't need any captcha libraries and let's you modify the widget's html easily. Also I added an option to pass remoteip to google api's verify method. How to use it: In your settings.py add: RECAPTCHA_PUBKEY = 'your recaptcha public key' RECAPTCHA_PRIVKEY = 'your recaptcha private key' After that just import and use ReCaptchaField in your form as you would any other field. That's it. *** Important *** If you want to have peace of mind in case google decided that the remoteip parametr is mandatory then: Derive every form that has the captcha field from ReCaptchaForm and when you create the form object after receiving POST/GET, pass a remoteip parameter like that: form = YourCaptchaForm(data=request.POST, remoteip=request.META['REMOTE_ADDR'])

  • forms
  • captcha
  • recaptcha
Read More

JsonObjectField

This fields.py file defines a new model field type, "JsonObjectField," which is designed to allow the storage of arbitrary Python objects in Django TextFields. It is intended primarily to allow the storage of Python dictionaries or list objects. As the name implies, it converts objects to JSON for storage; this conversion happens transparently, so from your model's perspective, the field stores and retrieves the actual objects.

  • model
  • json
  • database
  • object
Read More

is_in

I know in Django 1.2 we may acquire the same result using {% if value in arg %} but I need this filter in Django 1.1.

  • template
  • filter
  • django
  • contains
  • in
  • is
Read More

HTTP (basic) auth enabled (new-style) syndication framework feed class

This snipped provides a subclass of the syndication Feed class that supports HTTP authentication (basic auth). Feeds that should support authentication can inherit from this class instead from the Feed class. It is basically the implementation of [Snippet #243](http://djangosnippets.org/snippets/243/) ported to the new-style syndication framework feeds (for which decorators don't work). Usage: class ArticleFeed(HTTPAuthFeed): def items(self, obj): return Article.objects.all().order_by('-created')[:10] def item_title(self, item): return item.title def item_description(self, item): return item.description

  • feed
  • rss
  • syndication
  • http-auth
  • basic-auth
  • atom
  • protected
Read More

notify admin what fields have changed in form submission

here is some working code from a site that maintains profile information (address, phone number, etc) for users ("Partners"). this snippet handles the submitted form (after validation) and checks to see if any fields have been changed by the partner. if so, it shoots off an email to the admin showing the current profile information with changed fields marked with asterisks.

  • fields
  • forms
  • changed
Read More
Author: pjv
  • 0
  • 2

2955 snippets posted so far.