simple search with Q object you just pass a list of fields and the search string then it will come up with a object to use in a filter. This snippet is thanks to Julien Phalip
at [julienphalip.com](http://www.julienphalip.com/blog/2008/08/16/adding-search-django-site-snap/)
Example Usage of [Very basic CouchDB Paginator](http://www.djangosnippets.org/snippets/1208/)
An Example setup of CouchDB with django can be found at:
[Eric Florenzanos post about django+couchdb](http://www.eflorenzano.com/blog/post/using-couchdb-django/)
This is a very basic paginator for CouchDB ViewResults.
It's usage is similar to the django one.
**CouchPaginator** is almost like the django version with one exception: It's constructor needs an additional argument `pages_view` which is either a reduce result or an integer which holds the total number of objects across all pages.
*Example Map/Reduce for pages*:
> map = function(doc) {
> if(doc.type=="application" || doc.type==\"inquiry\"){
> emit([doc.meta.user.toLowerCase(), doc.type], 1);
> }
> reduce = function (doc, value, rereduce){
> return sum(value);
> }
**SimpleCouchPaginator** is much simpler and needs no total number and can only paginate by "next" and "previous" page. Use this if you don't have an reduce view which tells you the amount of total object.
An Example setup of CouchDB with django can be found at:
[Eric Florenzanos post about django+couchdb](http://www.eflorenzano.com/blog/post/using-couchdb-django/)
[See example usage](http://www.djangosnippets.org/snippets/1209/)
Validates and cleans UK telephone numbers. Number length is checked, and numbers are cleaned into a common format. For example, "+44 (0)1234 567890" will be stored as "01234 567890"
Can reject premium numbers (09123 123123) or service numbers (1471, 118 118) with `UKPhoneNumberField(reject=('premium', 'service'))`
Uses info from [Wikipedia](http://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom)
This class extends MultiWidget to create a widget that consists of HTML select elements for Django's forms.DateTimeFields. This results in a select elements with options for month, day, year, hour, minute, second, and (if using the twelve_hr option) meridiem.
# Default usage of SplitSelectDateTimeWidget
class TimeForm(Form):
dt = DateTimeField(widget=SplitSelectDateTimeWidget())
Another example hooks into the flexibility of the underlying Select Widgets:
class TimeForm(Form)
dt = DateTimeField(widget=SplitSelectDateTimeWidget(hour_step=2, \
minute_step=15, second_step=30, twelve_hr=True, years=[2008,2009,2010]))
The above example displays hours in increments of 2, minutes in increments of 15, and seconds in increments of 30. Likewise, only the years 2008, 2009,and 2010 are displayed in the years' options.
[See the blog entry](http://sciyoshi.com/blog/2008/nov/18/rails-mvc-controllers-django/)
Allows using controllers for views.
This allows for nice subclassing to override behavior of views. `Controller.urls` (see below) works fine for subclasses as well.
Similar to [snippet #1165](http://www.djangosnippets.org/snippets/1165/) except that it won't break reverse URL resolving and regex validation in URLs.
In `views.py`:
import mvc
class MyController(mvc.Controller):
@mvc.view('myview/$', 'myview')
def my_view(self):
# do something with self.request
return HttpResponse('something')
class Meta(mvc.Controller.Meta):
url_prefix = 'mycontroller-'
In `urls.py`:
from . import views
urlpatterns = patterns('',
# ... other urls here ...
*views.MyController.urls(r'prefix/')
)
Then the view `MyController.my_view` will be accessible from `'prefix/myview/'` and have the name `'mycontroller-myview'`, i.e. `reverse('mycontroller-myview')` will work as expected.
`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
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))
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.
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.
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.
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.
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
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.