Public
snipts » django
showing 1-20 of 74 snipts for django
-
∞ django groups and permissions
from django.contrib.auth.models import Group, Permission special_users = Group(name='Special Users') special_users.save() really_special_users = Group(name='Super Special Users') really_special_users.save() #Now you have two groups defined and can define permissions for them. Django associates #permissions with models (note: not model instances, but models). You’ll need to select a #model to apply the permissions to, and do a small dance with “ContentType” to find that #model’s content type: from django.contrib.contenttypes.models import ContentType somemodel_ct = ContentType.objects.get(app_label='myapp', model='somemodel') can_view = Permission(name='Can View', codename='can_view_something', content_type=somemodel_ct) can_view.save() can_modify = Permission(name='Can Modify', codename='can_modify_something', content_type=somemodel_ct) can_modify.save() #You’ve now defined two permissions and can associate them with your Groups: special_users.permissions.add(can_view) really_special_users.permissions = [can_view, can_modify] #Our groups and their associated permissions are ready to go. Now we just have to #associate these permissions with users: jack=User.objects.get(email='jack@test.com') jack.groups.add(special_users) jill=User.objects.get(email='jill@test.com') jill.groups.add(really_special_users) #We're all done. Now we can check the users' permissions: >>> jack.has_perm('myapp.can_view_something') True >>> jack.has_perm('myapp.can_modify_something') False >>> jill.has_perm('myapp.can_view_something') True >>> jill.has_perm('myapp.can_modify_something') True #And to use it in your templates: {% if perms.myapp.can_view_something %} Here is something for you to see. {% else %} Can't show you! {% endif %}
-
∞ Dynamic Django mod_wsgi hook files
# --- django.wsgi - in any project from some_common_module import wsgi_helper application = wsgi_helper.setup(__file__) # --- wsgi_helper.py - in some_common_module import os, sys import django.core.handlers.wsgi def setup(filename): project_root = os.sep.join(filename.split(os.sep)[:-2]) project_dir = None for path in os.listdir(project_root): # Find each dir off the root, and check it for settings.py path = os.path.join(project_root, path) if os.path.isdir(path): file = "".join([path, os.sep, "settings.py"]) if os.path.exists(file): # We have found /project_name/settings.py project_dir = path os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % path.split(os.sep)[-1] if not project_dir: raise Exception("Could not find project settings file! Checked path: %s" % path) if project_root not in sys.path: sys.path.insert(0, project_root) if project_dir not in sys.path: sys.path.insert(0, project_dir) return django.core.handlers.wsgi.WSGIHandler()
-
∞ django
hahaha -
∞ Highlight 404 on django runserver patch
Index: django/core/servers/basehttp.py =================================================================== --- django/core/servers/basehttp.py (revision 11655) +++ django/core/servers/basehttp.py (working copy) @@ -608,7 +608,10 @@ # Don't bother logging requests for admin images or the favicon. if self.path.startswith(self.admin_media_prefix) or self.path == '/favicon.ico': return - sys.stderr.write("[%s] %s\n" % (self.log_date_time_string(), format % args)) + if args[1] == '404': + sys.stderr.write("\033[31m[%s] %s\033[0m\n" % (self.log_date_time_string(), format % args)) + else: + sys.stderr.write("[%s] %s\n" % (self.log_date_time_string(), format % args)) class AdminMediaHandler(object): """
-
∞ Abstract paths in settings
""" This allows us to abstract the path of media files etc. This way, there is no need to place absolute paths. Credits (further reading): http://rob.cogit8.org/blog/2009/May/05/django-and-relativity-updated/ http://rob.cogit8.org/blog/2008/Jun/20/django-and-relativity/ """ import os.path PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) #Later on, all we need to do is: MEDIA_ROOT = os.path.join(PROJECT_DIR,'media')
-
∞ Dynamic redirection after login
login_url = '%s?next=%s' % (reverse('acct_login'), reverse('jumplog_index')) return HttpResponseRedirect(login_url)
-
∞ Mediatemple (dv) virtualenv.py activation script for mod_python, virtualenv, & django
# Mediatemple (dv) virtualenv.py activation script for mod_python, virtualenv, & django # based on http://mydjangoblog.com/2009/03/30/django-mod_python-and-virtualenv/ # # /path/to/virtualenv/home # $WORKON_HOME (eg. /home/.virtualenvs/) # # <virtualenv_name> # name of virtual environment. # virtualenv.py activate_this = '/path/to/virtualenv/home/<virtualenv_name>/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) from django.core.handlers.modpython import handler
-
∞ Mediatemple (dv) vhost config using mod_python, virtualenv, & django
# Mediatemple (dv) vhost config using mod_python, virtualenv, & django # based on http://mydjangoblog.com/2009/03/30/django-mod_python-and-virtualenv/ # # /path/to/virtualenv/home # $WORKON_HOME (eg. /home/.virtualenvs/) # # <virtualenv_name> # name of virtual environment. # # <project_container> # parent directory of django project (created by django-admin.py startproject). # # <project_name> # name of django project (eg. myblog). <Location "/"> SetHandler python-program PythonPath "['/path/to/virtualenv/home/<virtualenv_name>/bin', '/path/to/virtualenv/home/<virtualenv>/<project_container>'] + sys.path" PythonHandler virtualenv SetEnv DJANGO_SETTINGS_MODULE <project_name>.settings SetEnv PYTHON_EGG_CACHE /var/tmp PythonDebug On PythonInterpreter <project_name> </Location> <Location "/media"> SetHandler None </Location> <LocationMatch ".(jpg|gif|png)$"> SetHandler None </LocationMatch>
-
∞ django wsgi apache vhost
<VirtualHost *:8080> ServerAdmin user@domain.com ServerName domain.com ServerAlias sub.domain.com LogLevel warn ErrorLog /var/www/project/log/error.log CustomLog /var/www/project/log/access.log combined <Location "/"> SetHandler python-program PythonPath "['/var/www/project'] + sys.path" PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE project.settings PythonDebug Off PythonInterpreter project </Location> </VirtualHost>
-
∞ Validate email address (based on example from django source)
import re if re.match(r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"'r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', email_address, re.IGNORECASE): print "valid email" else: print "invalid email"
-
∞ Retrieve Django objects grouped by first letter of an attribute
""" ex: authors_by_letter = fetch_objects_by_letter(Author, 'name') returns: {u'A': [<Author: Ayn Rand>], u'J': [<Author: Jessica Simpson>], u'L': [<Author: Lord Voldemort>], u'T': [<Author: Trey Parker>]} """ def fetch_objects_by_letter(model, attr): qs = model.objects.all().order_by(attr) objs_by_letter = dict() for obj in qs: try: tmp = objs_by_letter[obj.__dict__[attr][0]] except KeyError: objs_by_letter[obj.__dict__[attr][0]] = list() objs_by_letter[obj.__dict__[attr][0]].append(obj) return objs_by_letter
-
∞ django iphone middleware
from django.conf import settings import re class iPhoneMiddleware(object): """ If the Middleware detects an iPhone/iPod the template dir changes to the iPhone template folder. """ def __init__(self): self.normal_templates = settings.TEMPLATE_DIRS self.iphone_templates = (settings.TEMPLATE_DIRS[0] + '/iphone',) def process_request(self, request): p = re.compile('iPhone|iPod', re.IGNORECASE) if p.search(request.META['HTTP_USER_AGENT']): # user agent looks like iPhone or iPod settings.TEMPLATE_DIRS = self.iphone_templates else: # other user agents settings.TEMPLATE_DIRS = self.normal_templates return
-
∞ Standalone Django script
from django.core.management import setup_environ import settings setup_environ(settings)
-
∞ fabric setup for django
# def localhost(): config.fab_hosts = ['localhost'] config.path = '/home/john/saebyn' config.env_path = '/usr/local/pythonenv/' config.env_name = 'SAEBYN-1' config.fab_user = 'john' def local_test(): localhost() local('source $(env_path)/$(env_name)/bin/activate; cd $(path)/website; ./manage.py runserver --settings=local_settings') def test(): """Production server settings""" config.fab_hosts = ['saebyn.info'] config.path = '/home/www/test.saebyn.info' config.fab_user = 'john' config.env_path = '/usr/local/pythonenv/' config.env_name = 'SAEBYN-1' def production(): """Production server settings""" config.fab_hosts = ['saebyn.info'] config.path = '/home/www/saebyn.info' config.fab_user = 'john' config.env_path = '/usr/local/pythonenv/' config.env_name = 'SAEBYN-1' def setup(): """ Setup a fresh virtualenv and install everything we need so it's ready to deploy to """ create_virtualenv() install_requirements() def create_virtualenv(): sudo('mkdir -p $(env_path)') sudo('cd $(env_path); virtualenv $(env_name)') sudo('cd $(env_path); chown -R $(fab_user) $(env_name)') def install_requirements(): """Install the required packages using pip""" run('cd $(env_path)/$(env_name); pip install -E . -r $(path)/requirements.txt') def deploy(): """Deploy the latest version of the site to the server and restart apache""" push_live() migrate() restart_apache() def push_live(): """Rebase 'live' using 'master', push it.""" local('git checkout live') local('git rebase master') local('git push origin live') local('git checkout master') def migrate(): """Run our migrations""" run('source $(env_path)/$(env_name)/bin/activate; cd $(path)/website; python manage.py syncdb --noinput --migrate') def restart_apache(): """Restart the web server""" sudo('/etc/init.d/apache2 restart')
-
∞ combine two django querysets and add type construct
from django.contrib.contenttypes.models import ContentType from itertools import chain featured_features = Feature.objects.filter(featured=True) featured_polls = Poll.objects.filter(featured=True) features = [] for feature in chain(featured_features, featured_polls): features.append(feature) for feature in features: feature.type = ContentType.objects.get_for_model(feature)
-
∞ Direct to template
from django.views.generic.simple import direct_to_template (r'^page/?$', direct_to_template, {'template': 'template.html'}),
-
∞ django wedding party guest model
from django.db import models class Guest(models.Model): CATEGORIES = ( ('WP', 'Wedding Party'), ('F', 'Family'), ('C', 'College'), ('W', 'Work'), ('FR', 'Friends'), ) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) category = models.CharField(max_length=255, choices=CATEGORIES) notes = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __unicode__(self): return u'%s %s' %(self.first_name, self.last_name)
-
∞ modify django admin field to use specific queryset and form widget
class ScheduleAdminForm(forms.ModelForm): profiles = forms.ModelMultipleChoiceField( widget = widgets.FilteredSelectMultiple('Profiles',False), queryset = Profile.active_objects.all(), help_text = "hey there") class Meta: model = Schedule class ScheduleAdmin(admin.ModelAdmin): form = ScheduleAdminForm
-
∞ Reverse a named URL from view
from django.core.urlresolvers import reverse return HttpResponseRedirect(reverse('todo-incomplete_tasks', args=[task.list.id, task.list.slug]))
-
∞ Find all groups a person is a member of:
u.groups.all()



Pro Django