This function takes a pattern with groups and replaces them with the given args and/or kwargs. Example:
IMPORTANT: this code is NOT to use replacing Django's reverse function. The example below is just to illustrate how it works.
For a given pattern '/docs/(\d+)/rev/(\w+)/', args=(123,'abc') and kwargs={}, returns '/docs/123/rev/abc/'.
For '/docs/(?P<id>\d+)/rev/(?P<rev>\w+)/', args=() and kwargs={'rev':'abc', 'id':123}, returns '/docs/123/rev/abc/' as well.
When both args and kwargs are given, raises a ValueError.
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)
This middleware makes the page load faster because it moves all tags <script> to the end of document.
When a tag <script> loads, it blocks parallel loading, so, the best practice is load them after load CSS and images.
To use it, just put in a file and add to your setting MIDDLEWARE_CLASSES.
Use it like below:
totals = MyClass.aggregate(
is_enabled_yes=CountCase('is_enabled', when=True),
is_enabled_no=CountCase('is_enabled', when=False),
count_if=CountCase('id', case="another_field in ('a','b')", when=True),
)
Just use it like below:
from downloaded_file import SumCase
MyClass.objects.aggregate(
sum1=SumCase('salary', case='salary < 4', when=True),
sum1=SumCase('salary', case='type', when='director'),
)
This function solve the issue of random.shuffle that is based only on randomized shuffling (that's not a real shuffling, because many times items returned aren't shuffled enough).
This function make a randomized shuffle and after this loops long the list resorting to avoid two items with a same value in a given attribute.
When shuffling is over and there are duplicates, they are leftover to the end (and you can remove them if you set 'remove_duplicates' to True)
Run it in a separated file to see it in action.
The widget for FileField and ImageField has a problem: it doesn't supports clear its value and it doesn't delete the old file when you replace it for a new one.
This is a solution for this. It is just for Admin, but you can make changes to be compatible with common forms.
The jQuery code will put an **<input type="checkbox">** tag next to every **<input type="file">** and user can check it to clear the field value.
When a user just replace the current file for a new one, the old file will be deleted.
This cache_page decorator can be used in replacement to Django's django.views.decorators.cache.cache_page.
It resolves two problems:
- invalidation (its cache key is not dependent of header nor request, then you can use model signals (or method 'put' in Google App Engine) to invalidate a URL or a list of them)
- easier to scale (can be used at once memcached server by many differente servers)
Feel free to show me where it can have problems or limitations.
**Updated and improved a lot**
This is a widget for decimal/money/currency fields on **Geraldo Reports**.
When you use Geraldo to write reports, decimal fields must be formatted using **get_value** lambda attribute, because ObjectValue doesn't know what mask you want to use.
With this widget, you just copy it into a common use Python file, import into your reports file and use it replacing ObjectValue on elements for fields you must be formatted as money format.
**Example:**
from geraldo import Report, ReportBand, ObjectValue
from utils.reports import DecimalObjectValue
class ReportCustomers(Report):
title = u'Customers List'
page_size = A4
class band_detail(ReportBand):
height = 0.5*cm
elements = [
ObjectValue(attribute_name='id', top=0.1*cm),
DecimalObjectValue(attribute_name='salary',
left=26.2*cm, top=0.1*cm, format='%0.03f'),
]
This is a widget for date/time fields on **Geraldo Reports**.
When you use Geraldo to write reports, date/time fields must be formatted using **get_value** lambda attribute, because ObjectValue doesn't know what mask you want to use.
With this widget, you just copy it into a common use Python file, import into your reports file and use it replacing ObjectValue on elements for fields you must be formatted as date/time format.
**Example:**
from geraldo import Report, ReportBand, ObjectValue, landscape
from utils.reports import DateTimeObjectValue
class ReportPhoneList(Report):
title = u'Phone List'
page_size = landscape(A4)
class band_detail(ReportBand):
height = 0.5*cm
elements = [
ObjectValue(attribute_name='id', top=0.1*cm),
DateTimeObjectValue(attribute_name='birth_date',
left=26.2*cm, top=0.1*cm, format='%m/%d/%Y'),
]
This exception is util when you want to raise an exception but want its message be shown as a message to the user, with no error 500 or 404 pages.
To use it, just append the middleware in the MIDDLEWARE_CLASSES setting and raises HttpMessage when necessary.
These field and widget are util for to those fields where you can put a star and end values.
It supports most of field types and widgets (tested with IntegerField, CharField and DateField / TextInput and a customized DateInput).
**Example of use:**
class FormSearch(forms.Form):
q = forms.CharField(max_length=50, label=_('Search for'))
price_range = RangeField(forms.IntegerField, required=False)
**Example of use (with forced widget):**
class FormSearch(forms.Form):
q = forms.CharField(max_length=50, label=_('Search for'))
price_range = RangeField(forms.IntegerField, widget=MyWidget)
This is a simple middleware that redirects the exactly URL requested with the correct domain. It is useful when you have more than one domain (most of cases with "www." or IP) to access a website.
To make it works, download the snippet file as the name "permanent_redirect.py" and add its path as the first item in MIDDLEWARE_CLASSES setting in settings.py.
Later you must inform a setting called `HTTP_HOST_DOMAIN` with the correct domain.