**UPDATE**: A more complete example is up on [GitHub](http://github.com/henriklied/django-twitter-oauth/tree/master)
Based around Simon Willison's [Fire Eagle oAuth](http://www.djangosnippets.org/snippets/655/), this will allow you to develop Twitter oAuth applications (…that is – if you're in the closed beta)
This blog post outlined how to get the user from the session key:
http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/
Unfortunately, it assumes DB-backed session and auth backends. This isn't required, so this snippet provides a backend-agnostic way to do the same thing.
>>> skey = 'ea0ed02d35d43aeaf20b3ef516f51396'
>>> user_from_session_key(skey)
<User: jeremyd>
This is based on a snippet contributed by zbyte64 ( RequireLoginMiddleware) but turned on its head. RequireLoginMiddleware enforces authentication for a subset of urls defined in settings.py. This middleware requires authentication for all urls except those defined in settings.py. The aim is to globally enforce site wide authentication without having to decorate individual views.
To use, add the class to MIDDLEWARE_CLASSES and then define the urls you don't need authentication for. These go in a tuple called PUBLIC_URLS in settings.py. For example:-
PUBLIC_URLS = (
r'project/application/login/',
r'project/application/signup/',
)
By default, authentication is not required for any urls served statically by Django. If you want to subject these to the same validation, add an entry to settings.py called SERVE_STATIC_TO_PUBLIC with a value of True.
This function emulates the file upload behaviour of django's admin, but can be used in any view. It takes a list of POST keys that represent uploaded files, and saves the files into a date-formatted directory in the same manner as a `FileField`'s `upload_to` argument.
Special thanks to all the authors of djangosnippets. It's my first contribution.
Maybe the method **online_users** could be better, but for now it's working for me.
Best Regards from Bolivia.
Alternative version of newform code for handling credit cards. Unlike the other two credit-card snippets (http://www.djangosnippets.org/snippets/764/ and http://www.djangosnippets.org/snippets/830/), this uses two drop-down boxes instead of text fields for the expiration date, which is a bit friendlier. It doesn't do as much checking as snippet #764 since we rely on the payment gateway for doing that. We only accept Mastercard, Visa, and American Express, so the validation code checks for that.
**This code will throw deprecation warnings in newer Django checkouts - see the http://www.djangosnippets.org/snippets/773/ for an improved version that should work with the recent trunk.**
objects = MyModel.objects.all()
paginator = DiggPaginator(objects, 10, body=6, padding=2, page=7)
return render_to_response('template.html', {'paginator': paginator}
{% if paginator.has_next %}{# pagelink paginator.next #}{% endif %}
{% for page in paginator.page_range %}
{% if not page %} ...
{% else %}{# pagelink page #}
{% endif %}
{% endfor %}
http://blog.elsdoerfer.name/2008/03/06/yet-another-paginator-digg-style/
This is a customized version of the default `for` template tag which takes an optional `{% else %}` clause that will be displayed if the given array is empty.
from django.template import *
>>> t1 = Template("""
{% load mytags %}
{% for athlete in athlete_list %}
{{ athlete }}
{% else %}
No athlete in list!
{% endfor %}
""")
>>> c1 = Context(
{'athlete_list':
['me', 'myself', 'I']
})
>>> t1.render(c1)
u'me myself I '
>>> c2 = Context({})
>>> t1.render(c2)
u'No athlete in list!'
If you want to automatically override the builtin `for` template-tag add it to the builtins:
from django.template import add_to_builtins
add_to_builtins('python.path.to.mytags')
A URL field specifically for images, which can validate details about the filesize, dimensions and format of an image at a given URL, without having to read the entire image into memory.
Requires [Python Imaging Library](http://www.pythonware.com/library/pil/).
*4th October, 2008* - updated for 1.0 compatibility.
The rationale behind this decorator is described in django-users google group.
Usage:
=== urls.py ===
urlpatterns = patterns('',
(r'^', include('apps.app1.views')),
(r'^app2', include('apps.app2.views')),
)
=== apps/app1/views/__init__.py ===
@url(r'^index/$')
def index(request):
...
@url(r'^news/$')
def news(request):
...
urlpatterns += include_urlpatterns(r'^members', 'apps.app1.views.members')
=== apps/app1/views/members.py ===
@url(r'^profile/$)
def profile(request):
....
@url(r'^secure/$)
def secure(request):
...
@url(r'^path1/$', '^path2/$') # you can specify several patterns
def multipath_view(request):
...
def helper(): # easily distinguishable - no @url!
...
Summarizing, the benefits are:
* no more creating and supporting urlpattern maps (less files, less code, more DRY)
* have the url associated with a view in-place
* easily see if a function is a view
* fully compatible with other chained decorators
This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript.
**Example** (models.py):
from django.db import models
from jsonfield import JSONField
class Sequence(models.Model):
name = models.CharField(maxlength=25)
list = JSONField()
**Example** (shell):
fib = Sequence(name='Fibonacci')
fib.list = [0, 1, 1, 2, 3, 5, 8]
fib.save()
fib = Sequence.objects.get(name='Fibonacci')
fib.list.append(13)
print fib.list
[0, 1, 1, 2, 3, 5, 8, 13]
fib.get_list_json()
"[0, 1, 1, 2, 3, 5, 8, 13]"
*Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.
Tag library that provides support for *macros* in Django templates.
**Usage example:**
**0)** Save this file as
<yourapp>/templatetags/macros.py
**1)** In your template load the library:
{% load macros %}
**2)** Define a new macro called 'my_macro' with parameter 'arg1':
{% macro my_macro arg1 %}
Parameter: {{ arg1 }}
{% endmacro %}`
**3a)** Use the macro with a String parameter:
{% usemacro my_macro "String parameter" %}
**3b)** or with a variable parameter (provided the context defines 'somearg' variable, e.g. with value "Variable parameter"):
{% usemacro my_macro somearg %}
**3c)** **!!NEW!!** `usemacro` now also supports filters attached to parameters:
{% usemacro my_macro "lowercase parameter"|upper %}
Output of the above code would be:
Parameter: String parameter
Parameter: Variable parameter
Parameter: LOWERCASE PARAMETER
**4)** **!!NEW!!** Alternatively save your macros in a separate file, e.g. "mymacros.html" and load it into the current template with:
{% loadmacros "mymacros.html" %}
Macros can take *zero or more arguments* and both context variables and macro arguments are resolved in macro body when used in `{% usemacro ... %}` tag.
Bear in mind that Macros are local to each template file and are not inherited through `{% extends ... %}` blocks.
Flash message add-on for Django. Uses sessions. Behavior is such that you set a flash message in a view. That message is stored in the sesssion. Then whenever it is that the message gets displayed, it is removed from the session (never to be heard from again)
**Installation:**
In your settings, enable the following items.
TEMPLATE_CONTEXT_PROCESSORS
django.core.context_processors.request
MIDDLEWARE_CLASSES
django.contrib.sessions.middleware.SessionMiddleware
Then put it into a file called flash.py in your templatetags directory.
**Usage:**
It's pretty simple. Do something like this in your view ..
>>>request.session['flash_msg'] = 'Your changes have been save'
>>>request.session['flash_params'] = {'type': 'success'}
And maybe put something like this in your template
{% load flash %}
{% flash %}
<h2>{{ params.type }}</h2>
{{ msg }}
{% endflash %}
It also support a flash template, you can specify a file
FLASH_TEMPLATE in your settings file and then that file will be rendered with msg and params as available variable.
Usage for this would simply be `{% flash_template %}` and then you gotta make a template file that does whatever you like.
Outside of that just be aware you need the Django session middleware and request context installed in your app to use this.
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.