usage :-
put it in python path and refer to it from settings.py
`THUMBNAIL_BACKEND = 'full.import.path.to.SEOThumbnailBackend'`
Took me a bit to figure it out since i couldn't find an existing example code for it.
Adds filtering by ranges of dates in the admin filter sidebar.
[https://github.com/coolchevy/django-datefilterspec](https://github.com/coolchevy/django-datefilterspec)
[http://coolchevy.org.ua](http://coolchevy.org.ua)
https://github.com/coolchevy/django-datefilterspec/raw/master/datefilter.png
Example:
`
from django.db import models
import datefilterspec
class Person(models.Model):
date = models.DateTimeField(default=datetime.datetime.now)
date.date_filter = True
class Admin:
list_filter = ['date']
Method which gets a chunk of HTML to perform standard Google Analytics tracking as well as a noscript version. Very useful for finding out what percentage of your users do not have JavaScript support.
This is Python port of the PHP example here: [http://andrescholten.net/google-analytics-zonder-javascript/](http://andrescholten.net/google-analytics-zonder-javascript/)
To use, you need to put the following into your settings file:
GOOGLE_ANALYTICS_ID = 'UA-1234567-1'
GOOGLE_ANALYTICS_DOMAIN = 'example.com'
Save the code as app_name/templatetags/urlbuilder.py. Supply your view with a dictionary of "default" query params, likely taken from the request. Then, in the template:
`{% load urlbuilder %}
{% url some-url as base_url %}`
That sets you up. Then you can make links. For example:
<th><a href="{% build_url base_url query_params sort=name %}">Name</a></th>
Say query_params has:
page: 2,
filter: active,
sort: id
The above tag would spit out /base/url?page=2&filter=active&sort=name
The tag also has support for using a variable as the replacement key. Say "filter_key" is a variable available to the template with the value "filter":
{% build_url base_url query_params filter_key default %}
Using the above example, that would output /base/url?page=2&filter=default&sort=id
Due to compliance requirements in the financials industry we needed to log every request a user made to our system, the action taken (view function) and response from the server.
I found a lot of other logging solution bit most revolved around debugging and DB query logging. I needed to be able to tell what a user did while being logged in as much detail as I could with out tracking the mouse pointer position on screen.
So I created this (, *my first* ,) middleware. Its very simple really. keeping track of a request, view_func and response object in a single model called Record (models.py file included in the code).
The fields I used are optimized to what I intend to show in the UI I am planning for this model. Depending on how you use the doc string of your views they can be tapped to explain to the user what each request/func/responce group in a session is meant to do.
There were a few gotcha's:
1. I only care about authenticated requests. So I added the 'quest.user.is_authenticated()' test.
2. I did not care about the favicon request so I skipped them.
2. The actual login request is not authenticated while the response is. This caused the process_response/view to look for a record that is not there. So I added the 'except ObjectDoesNotExist' to skip this case.
I added one bell: Logging a full HTML reply is wasteful and mostly useless. I added two values in the setting files. LOGALL_LOG_HTML_RESPONSE to toggle if we want to log them or not. And LOGALL_HTML_START to describe what a full HTML starts with. Personally I use the first few characters of my base.html template that all the rest of my templates expend. I simplified the code to the left for readability.
Just extends your models from this One... is abstract so, it will not generate a table.
Now, in your urls.py do this:
from django.conf.urls.defaults import *
from animals.models import Dog, Cat, Bird
urlpatterns = patterns('animals.views',
url(r'^$', 'index', {},Dog._meta.app_label),
)
dog=Dog()
cat=Cat()
bird=Bird()
urlpatterns+=dog.build_generic_CRUD_urls(Dog)
urlpatterns+=cat.build_generic_CRUD_urls(Cat)
urlpatterns+=bird.build_generic_CRUD_urls(Bird)
then you can create the templates, and get the urls like this:
{{ object.get_absolute_url }} View
{{ object.get_update_url }} Edit
{{ object.get_delete_url }} Delete
{{ dummy_object.get_create_url }} Create
dummy_object is a quick and dirty solution until I find some better...
With all these you can create 54 functional and low detail CRUDS in one hour. :D
Enjoy!
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)
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'])
This is adapted from [rodnsi's version](http://djangosnippets.org/snippets/1818/) to work with Django 1.2 (as django.contrib.admin came with jQuery built in as of 1.2).
Very straightforward way to display a thumbnail in the admin using [django-thumbnails-works](http://pypi.python.org/pypi/django-thumbnail-works) .
django-thumbnails-works requires [cropresize](http://pypi.python.org/pypi/cropresize/#downloadsInstaller) (which requires and installs PIL).
Add 'thumbnail_works'to INSTALLED_APPS in settings.py and here you go.
Tested in django 1.3 alpha.
Allows url patterns to include a boolean indicating whether a view requires
TLS(SSL). The accompanying middleware handles the redirects needed to make
sure that it upholds this requirement.
**WARNING**: this monkey-patches some Django internals and is difficult to test
since Django's TestClient does not support TLS. If you use this make sure you
test it thouroughly.
Add this to your Django settings
USE_TLS = True # The default for this setting is False.
URL pattern usage
url(r'^login$', 'myproject.login.index',
{'require_tls': True}, name='login-index'),
Use `require_tls` True to force the middleware to perform redirects needed to
make sure your are serving this view using https.
Use `require_tls` False to force the middleware to redirect to http. Be
careful with this setting, this may not behave as you expect. If you don't
care if the view is served via https or http then do not include
`require_tls` in the pattern.
If you wish to have every view in the site served with TLS then specify the
following Django setting
ALWAYS_USE_TLS = True # Django setting, use TLS for every view
This is an expanded version of ["Resolve URLs to view name"](http://djangosnippets.org/snippets/1378/) without the monkey-patching.
Simply pass in a URL such as '/events/rsvp/some_conference/' and you'll get back the view name or function (if name isn't available) and the arguments to it, eg 'events_rsvp', [], {'event_slug':'some_conference'}.
Example (blatantly copied from previous snippet):
=== urlconf ====
urlpatterns = patterns(''
(r'/some/url', 'app.views.view'),
url(r'/some/other/(?P<url>\w+)', 'app.views.other.view', name='this_is_a_named_view'),
url(r'/yet/another/(?P<url>\w+)/(\d+)', 'app.views.yetanother.view', name='one_with_args'),
)
=== example usage in interpreter ===
>>> from some.where import resolve_to_name
>>> print resolve_to_name('/some/url')
('app.views.view',[],{})
>>> print resolve_to_name('/some/other/url')
('this_is_a_named_view',[],{'url':'url'})
>>> print resolve_to_name('/yet/another/url/5')
('one_with_args',[5],{'url':'url'})
From [fahhem.com](http://fahhem.com/) and [Recrec Labs](http://recreclabs.com/)
If your URL pattern looks like:
`urlpatterns = patterns('django.views.generic.create_update',
url(r'^obj/(?P<obj_id>\d+)/new_thing$', create_object, {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', extra_context: {:this":"that"}),
)`
You will receive an error, because the create_update view doesn't have a parameter called "obj_id". Supposing you want that variable in the URL, and furthermore let's say you wanted to do something with it in the template. With this function, you can wrap the view, and add the parameter capture_to_context, which maps URL variables to template variables:
`urlpatterns = patterns('django.views.generic.create_update',
url(r'^obj/(?P<obj_id>\d+)/new_thing$', view_url_vars_to_context(create_object), {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', 'url_vars_to_context':{'obj_id':'objID'}, extra_context: {:this":"that"}}),
)`
Now objID will be a variable in your template, with the value given to obj_id.
This is good for generic views, but there's no reason you couldn't use it for your own views if you really wanted, as long as you had an "extra_context" parameter.
Prevents error flooding on high traffic production sites. Particularly useful to prevent clogging email servers etc.
See [discussion](http://groups.google.com/group/django-developers/browse_thread/thread/1dabc9139dd750ca/1d86fdca23189a7d?lnk=gst&q=error#1d86fdca23189a7d) and [closed ticket](http://code.djangoproject.com/ticket/11565).
Uses memcache if it can, or falls back to local, in-process memory where unavailable (down, etc).
Tweak to your needs using setting ERROR_RATE_LIMIT (seconds).
Requires Django 1.3+ or trunk r13981+
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.