Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

forced logoff for banned user

diurétique lasix 40mg generique achat en ligne sans ordonnance
Vente en ligne Cialis generique, commander Viagra ou Levitra pas cher bas prix.
class UserForceLogoffMiddleware(object):
    def process_request(self, request):
        from django.contrib.auth import logout
        if request.user and request.user.is_authenticated():
            key = "userbanned_" + str(request.user.id)
            is_banned = cache.get(key)
            if is_banned:
                logout(request)
                cache.delete(key)
                return HttpResponseRedirect('/accounts/login/')

Django: using properties on models

http://www.djangoproject.com/documentation/models/properties/

// insert code here..

Django and JSON

// This function takes anything which can be dumped into JSON and returns an HTTP response of it, with the right Content-type header.

def json_response(something):
    from django.utils import simplejson
    return HttpResponse(simplejson.dumps(something),
                        content_type='application/json; charset=UTF-8')

decorator for checking that an object belongs to the user trying to access it

# private is a decorator which checks if an object thas is being accessed
# belongs to the user trying to access it
# Arguments:
# alt_func - function to be returned if a user has no right to access an object
# model_class - model class to which an object belongs
# search_field - a field by which an object is selected (e.g. slug)
# (should be unique)
# search_value - the name of the wrapped view function argument, which contains
# the value the search_field should have
# user_field - the name of the object field which holds the reference to
# the object's owner(s) (ForeignKey or ManyToManyField)
def private(alt_func, model_class, search_field, search_value, user_field):
    def _private(view_func):
        def __private(request, *args, **kargs):
            if not request.user.is_authenticated():
                return alt_func(request)
            try:
                kwargs = {search_field: kargs[search_value]}
                obj = model_class.objects.get(**kwargs)
                model_user_field = getattr(obj, user_field)
                if model_user_field.__class__.__name__ == "User":
                    if model_user_field != request.user:
                        raise UnauthorizedAccess()
                elif model_user_field.__class__.__name__ == 'ManyRelatedManager':
                    if not request.user in model_user_field.all():
                        raise UnauthorizedAccess()
                else:
                    raise AnyError()
            except:
                return alt_func(request)
            else:
                kargs['obj'] = obj
                return view_func(request, *args, **kargs)
        return __private
    return _private

Django: adding new admin_tags

// First: create a file under djangoapp/templatetags where you define your tags [e.g.: myadmin_tags.py]:


from django import template 
from poms.pomsapp import models

register = template.Library() 

# for People template

@register.inclusion_tag('admin/snippets/personfactoid_info.html') 
def display_personfactoids(person_id): 
    person = models.Person.objects.get(id__exact=person_id) 
    # factoids = models.Factoids.objects.filter(people=person)
    return { 'person': person }


// Second: create the html snippets that get loaded in those tags [e.g., personfactoid_info.html]:


{% if person.assocfactoidperson_set.all %}

<b>Person associated to factoids:</b></br />

	<table>
	  <tr>
	    <th>Record ID</th>
		<th>Type</th>
	    <th>Short Summary</th>
		<th>Role</th>
	    <th>Source</th>
	  </tr>

	{% for a in person.assocfactoidperson_set.all %}
	  <tr>
	    <td>{{a.factoid.id}}</td>
		<td>{{a.factoid.get_right_subclass.0}}&#160;&#160;&#160;&#160;</td>
	    <td><a href="{% url factoid_detail a.factoid.id %}" title="click to show">{{a.factoid}}</a></td>
	    <td>{{a.role}}</td>
	    <td><a href="{% url source_detail a.factoid.sourcekey.id %}" title="click to show">{{a.factoid.sourcekey}}</a></td>
	  </tr>
	{% endfor %}

	</table>
	
	<br /><hr><hr><hr><br />
{% endif %}	



// Third: in mytemplates/admin/ modify change_form.html (if you don't have it just copy it from the django-admin app). You must add a placeholder for the new templatetags (probably you want to add it at the bottom of the page):


........

{% block related_items_block %}{% endblock %}

........




// FOurth: create a new change_form.html in the same directory as above, but under your model template [e.g., mytemplates/admin/myapp/mymodel/change_form.html] so to override the behaviour just for that. The 'object_id' variable is passed by the admin template by default:


{% extends "admin/change_form.html" %} 
{% load myadmin_tags %} 
{% block related_items_block %}
<h2>Additional information:</h2><br />

  	{% if object_id %}
		{% display_personfactoids object_id %}
	{% endif %} 
	
 {% endblock %}


Django: access the attributes of a model dynamically

// example: a method on a model that outputs a list of tuples with (attribute_name.verbose, attribute_value)

	def attrs_verbose(self):
		model = self.__class__
		# using this form: Record._meta.get_field('created_by').verbose_name
		items = []
		for k, v in self.__dict__.items():
			try:
				x = model._meta.get_field(k).verbose_name
			except:
				x = k
			items += [(x, v)]
		items.sort()
		return items

Django kwargs

// description of your code here


class Entry( models.Model ):
    user = models.ForeignKey( User, related_name = 'user_relation' )
    category = models.ForeignKey( Category, related_name = 'category_relation' )
    title = models.CharField( max_length = 64 )
    entry_text = models.TextField()
    deleted_datetime = models.DateTimeField()



kwargs = {
    # you can set common filter params here
}

# will return entries which don't have a deleted_datetime
if exclude_deleted:
    kwargs[ 'deleted_datetime__isnull' ] = True

# will return entries in a specific category
if category is not None:
    kwargs[ 'category' ] = category

# will return entries for current user
if current_user_only:
    kwargs[ 'user' ] = request.user

# will return entries where titles match some search query
if title_search_query != '':
    kwargs[ 'title__icontains' ] = title_search_query

# apply all filters and fetch entries that match all criteria
entries = Entry.objects.filter( **kwargs )

Django Q objects

// description of your code here

from django.db.models import Q

Publisher.objects.filter(Q(state_province="CA") | Q(state_province="AZ"))

#or also more programmatically:

args = ( Q( title__icontains = 'Foo' ) | Q( title__icontains = 'Bar' ) )
entries = Entry.objects.filter( *args)

create a template tag django

//
example of some of the stuff in ellington.core.parts.templatetags to make life easier when creating tags...

This is pretty beta, so at this point some stuff might not function as desired.. The function/model doc's in the code are ok..


*above is a 'should work' version of the tag you were talking about friday*

the above code would create a template tag {% get_gallery_list %} which takes to kwarg's .. (categories, as), categories will be passed into the GalleryByCategoryNode as is, but as will be remapped to variable_name since as is a reserved keyword in python... Your class variable self.categories__in will get turned into the galleries.get_list(categories__in=()) .. That variable name might have to be changed to self.category__slug__in, .....etc.. to work...

yeah basically it creates the whole def get_gallery_list(parser, tokens):
#.. do a bunch of argument parsing
return MyNodeClass(**kwargs)


from ellington.core.parts.templatetags import GetListNode, get_kwarg_templatetag
    class GalleryByCategoryNode(GetListNode):
    model = Gallery
    def __init__(self, categories='', variable_name='gallery_list'):
        self.categories__in = categories.split(',')


register.tag(get_kwarg_templatetag(
     name='get_gallery_list',
     doc="""Example: {% get_gallery_list categories sports,outdoors %}
        from django.core import template
        t = template.Template("{% load photogalleries %} {% get_gallery_list categories sports as      my_galleries%}{{ my_galleries }}")
     """,
     node_class=GalleryByCategoryNode,
     remap_arguments=(('as', 'variable_name'),),

LightTPD subdomain rewrite, Backpack/Basecamp style.

Rewrites test.example.com/example/path/ to example.com/test/example/path/

This example show the values being passed to FCGI for use by Django.


$HTTP["host"] =~ "([^.]+)\.example\.com" {
  server.document-root = "/users/home/username/domains/example.com/web/public"
  server.errorlog = "/users/home/username/var/log/lighttpd.example_com.error.log" 
  accesslog.filename = "/users/home/username/var/log/lighttpd.example_com.access.log" 

  fastcgi.server = (
    "/main.fcgi" => (
      "main" => (
        "socket" => "/users/home/username/tmp/django/example_com.socket"
      )
    )
  )

  url.rewrite-once = ( "^(/.*)$" => "/main.fcgi/%1/$1" )
  server.error-handler-404 = "/main.fcgi" 
}