Perhaps this is blindingly obvious but I spent a while trying to get this, before figuring out that when a each item of an iterated ValuesQuerySet is a dict.
Useful for serialising to JSON or XML etc.
Tightens up response content by removed superflous line breaks and whitespace.
By Doug Van Horn
---- CHANGES ----
v1.1 - 31st May 2011
Cal Leeming [Simplicity Media Ltd]
Modified regex to strip leading/trailing white space from every line, not just those with blank \n.
---- TODO ----
* Ensure whitespace isn't stripped from within <pre> or <code> or <textarea> tags.
Assuming you have defined STATIC_ROOT correctly in settings.py, and have installed staticfiles_urlpatterns() in urls.py (as demoed in the code, taken from Django's staticfiles docs), the code from static_root_finder.py can be used to simply serve static files in development from STATIC_ROOT directly, avoiding complicated setups in case we just want to have a bunch of static files in one directory.
This view acts as an extension to the object_detail generic view in django.views.generic.object_list. The standard generic view can only filter the queryset by object_id or slug; this view allows you to filter by any parameter you like, as well as multiple parameters.
The usage is the same as the standard object_detail view except that you must also give the parameter 'filters', which should be an array of what you would like to filter the url values as, and instead of 'slug' or 'object_id' as the regex parameter in the URL, use 'value1', 'value2', etc.
Example: If you have a list of companies, each with multiple branches, you may want a branch details page. A URL for this may look as follows: http://www.mysite.com/company/company-slug/branch-slug/. To implement this simply use the urlpattern example give,
In templates sometimes you need to display some menu by checking whether the user is logged in or not. So use the above filter as shown below
{% with request|check_login as logout %}
{% if logout%}
display something....
{% endif %}
{% endwith %}
This is auth_data_required decorator analogous to login_required where authentication data must come in POST of request.
It's useful for API. I took the idea from [Tumblr API](http://www.tumblr.com/docs/en/api).
Tag for iterating through the fields of an object from a template.
The tag is passed two string arguments, the name of the model to use (which is then looked up in the context dictionary), and the format string. The format string should include two string place holders.
The tag will output each field name and value according to the format string supplied.
The above conf file the easiest way to point the env and the settings together , the user has to point the django.wsgi file with the correct path and it should work fine and one can directly run it in apache
An emulation of "table per hierarchy" a.k.a. "single table inheritance" in Django. The base class must hold all the fields. It's subclasses are not allowed to contain any additional fields and optimally they should be proxies. They however may provide additional methods to operate on the declared field. The presented solution supports implicit inheritance, even across ForeignKeys, and ManyToManyFields. No additional database hits are imposed.
A template loader useful for writing templates with carefully controlled newlines and spaces while retaining readable template source code formatting.
Start the template with PTFTAG (`{#ptfable#}`, here) to allow it to be processed. Common problems with doing it to most templates as-is is use of newlines to separate words and multiple spaces between tags where spaces are still needed (which is problematic with `spaceless` tag as well).
Currently intended as a template loader wrapper, and is suggested to be used with cached loader. Example settings.py configuration:
_lp = lambda lo, *ar: (lo, ar,) # loader, arguments
TEMPLATE_LOADERS = (
_lp('django.template.loaders.cached.Loader', # cache
_lp('ptf.template.ptftemplateloader.Loader', # ptf
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
#'django.template.loaders.eggs.load_template_source'
), # ptf
), # cache
)
(change `ptf.` to wherever in python path you've put it).
You might also need couple of simple template tags for explicitly inserting newlines or whitespaces:
def br():
return "\n"
br = register.simple_tag(br)
# XHTML-XMPP-template compatible.
def brx():
return "<br />\n"
brx = register.simple_tag(br)
def ws():
return " "
ws = register.simple_tag(ws)
.
This is extremely simple decorator to add possibility to upload files with name specific in some object field. For example image with same name as object slug.
Sample **model**:
class Test(models.Model):
image = models.ImageField(\
upload_to=upload_to_dest(path='pics/', \
human_readable_field='hrname'))
hrname = models.CharField( \
max_length=128, \
blank=True, default='')
Sample **form** for admin:
FNAME_EXP = re.compile('^[A-Za-z0-9\-\_]+$')
class TestAdminForm(forms.ModelForm):
hrname = forms.RegexField(
label="Human Readable File Name", \
regex=FNAME_EXP, \
help_text="""Allowed only latin alphabet
(upper and lower cases),
underscore and minus
characters. PLEASE, DO NOT INCLUDE
EXTENSION OF THE FILE.
Sample: test-this-file""", \
required=False)
class Meta:
model = Test
Sample *admin.py* for *Test* model:
class TestAdmin(admin.ModelAdmin):
form = TestAdminForm
admin.site.register(Test, TesetAdmin)
Note: This concerns django 1.3 but the tags does not yet exist.
We have a couple of apps, including 3rd party apps, that have the 'static' files in 'media' dirs. These files aren't found with collectstatic in django 1.3. With this snippet they will be.
To use it:
* paste the code in a file e.g. yourproject/finders.py.
* include the finder in settings.STATICFILES_FINDERS:
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'yourproject.finders.AppMediaDirectoriesFinder',
)
* ./manage.py collectstatic -n -l
This function mangles a generated form class to remove the Hold down "Control", or "Command"... messages from the help text. This is really a dirty hack awaiting a proper solution to [Django ticket 9321](http://code.djangoproject.com/ticket/9321).
This function can be useful for forms in the admin interface that use custom widgets. Basic usage:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
class MyAdmin(admin.ModelAdmin):
form = remove_holddown(MyModelForm, ('field1', 'field2'))
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.