IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » django The latest public django snipts.

showing 1-20 of 86 snipts for django
  • Use template filters in a script
    # Convert existing plain text description for workshops to HTML.
    # Loop through all workshops, extract the description field, 
    # run it through Django's linebreaks template filter, and save.
    
    from django.utils.html import linebreaks
    
    wkshps = Workshop.objects.all()
    
    for w in wkshps:
        w.desc = linebreaks(w.desc)
        w.save()
    

    copy | embed

    0 comments - tagged in  posted by shacker on Sep 02, 2010 at 5:46 p.m. EDT
  • Generate SECRET_KEY value
    from random import choice
    
    print ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
    

    copy | embed

    0 comments - tagged in  posted by jonbiddle on Aug 31, 2010 at 2:01 p.m. EDT
  • Re-check pass form
    class PasswordCheckForm(forms.Form):
        password = forms.CharField(widget=forms.PasswordInput)
        
        def __init__(self, user, *args, **kwargs):
            self.user = user
            super(PasswordCheckForm, self).__init__(*args, **kwargs)
        
        def clean(self):
            password = self.cleaned_data.get('password')
            if self.user.check_password(password):
                raise forms.ValidationError(_('Password is incorrect.'))
            
            return self.cleaned_data
    
    def recheck_pass(request, template_name='registration/recheck_pass.html',
                     redirect_field_name=REDIRECT_FIELD_NAME,
                     authentication_form=PasswordCheckForm):
        
        redirect_to = request.REQUEST.get(redirect_field_name, '')
        
        if request.method == 'POST':
            form = authentication_form(request.user, request.POST)
            
            if form.is_valid():
                if not redirect_to or ' ' in redirect_to:
                    redirect_to = settings.LOGIN_REDIRECT_URL
                if '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
                    redirect_to = settings.LOGIN_REDIRECT_URL
        else:
            form = authentication_form(request.user)
            
        return render_to_response(template_name, {
            'form': form,
        }, RequestContext(request))
    

    copy | embed

    0 comments - tagged in  posted by TomL on Aug 25, 2010 at 10:51 a.m. EDT
  • Ordering in Django templates
    # If you don't have access to the queryset to do an order_by, you can still
    # do limited ordering in the template with dictsort and dictsortreversed 
    # template filters
    
        {% for s in profile.story_set.all|dictsortreversed:"id" %}
          {{s}}
        {% endfor %}
    

    copy | embed

    0 comments - tagged in  posted by shacker on Aug 10, 2010 at 4:52 p.m. EDT
  • 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]))
    

    copy | embed

    0 comments - tagged in  posted by shacker on May 25, 2010 at 3:45 p.m. EDT
  • Detect presence of a certain field in POST
    if request.POST.has_key('comment-body'):
    

    copy | embed

    0 comments - tagged in  posted by shacker on May 25, 2010 at 3:44 p.m. EDT
  • In a template, count objects related to an item
    {{ task.comment_set.all.count }}
    

    copy | embed

    0 comments - tagged in  posted by shacker on May 25, 2010 at 3:43 p.m. EDT
  • Exclude instances of one model that are already present in another model:
    newquestions = TriviaQuestion.objects.exclude(pk__in=GameHistory.objects.all().values_list('pk',flat=True)
    

    copy | embed

    0 comments - tagged in  posted by shacker on May 25, 2010 at 3:40 p.m. EDT
  • Portable paths for Django
    import os
    
    CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8')).replace('\\', '/')
    
    TEMPLATE_DIRS = (
        os.path.join(CURRENT_PATH, 'templates'),
    )
    

    copy | embed

    0 comments - tagged in  posted by gotoplanb on Apr 27, 2010 at 12:09 p.m. EDT
  • exemplo de uso do modeladmin do django com jquery
    from django.contrib import admin
    
    class ModeloAdmin(admin.ModelAdmin):
        class Media:
            js = ("js/jquery.js", "js/my_code.js",)
    

    copy | embed

    0 comments - tagged in  posted by italomaia on Apr 21, 2010 at 7:54 p.m. EDT
  • slugifyuniquely for django
    from django.template.defaultfilters import slugify
    from django.db.models import Q
    import re
    
    def SlugifyUniquely(value, model, slugfield="slug"):
            """Returns a slug on a name which is unique within a model's table
    
            This code suffers a race condition between when a unique
            slug is determined and when the object with that slug is saved.
            It's also not exactly database friendly if there is a high
            likelyhood of common slugs being attempted.
    
            A good usage pattern for this code would be to add a custom save()
            method to a model with a slug field along the lines of:
    
                    from django.template.defaultfilters import slugify
    
                    def save(self):
                        if not self.id:
                            # replace self.name with your prepopulate_from field
                            self.slug = SlugifyUniquely(self.name, self.__class__)
                    super(self.__class__, self).save()
    
            Original pattern discussed at
            http://www.b-list.org/weblog/2006/11/02/django-tips-auto-populated-fields
            """
            suffix = 0
            potential = base = slugify(value)
            while True:
                    if suffix:
                            potential = "-".join([base, str(suffix)])
                    if not model.objects.filter(**{slugfield: potential}).count():
                            return potential
                    # we hit a conflicting slug, so bump the suffix & try again
                    suffix += 1
    
    def normalize_query(query_string,
                        findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
                        normspace=re.compile(r'\s{2,}').sub):
        ''' Splits the query string in invidual keywords, getting rid of unecessary spaces
            and grouping quoted words together.
            Example:
    
            >>> normalize_query('  some random  words "with   quotes  " and   spaces')
            ['some', 'random', 'words', 'with quotes', 'and', 'spaces']
    
        '''
        return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] 
    
    def get_query(query_string, search_fields):
        ''' Returns a query, that is a combination of Q objects. That combination
            aims to search keywords within a model by testing the given search fields.
    
        '''
        query = None # Query to search for every search term        
        terms = normalize_query(query_string)
        for term in terms:
            or_query = None # Query to search for a given term in each field
            for field_name in search_fields:
                q = Q(**{"%s__icontains" % field_name: term})
                if or_query is None:
                    or_query = q
                else:
                    or_query = or_query | q
            if query is None:
                query = or_query
            else:
                query = query & or_query
        return query
    

    copy | embed

    1 comment - tagged in  posted by nick on Apr 06, 2010 at 10:24 a.m. EDT
  • Django image proxy
    def proxy(request):
        url = request.GET.get('url')
        if url is not None:
            try:
                img = urllib2.urlopen(url)
                return HttpResponse(img.read(), mimetype=img.info().type)
            except urllib2.URLError:
                return HttpResponse('Proxy failed.', status=404)
    

    copy | embed

    0 comments - tagged in  posted by bobthabuilda on Apr 05, 2010 at 8:44 p.m. EDT
  • load grappelli fixtures
    python manage.py loaddata $VIRTUAL_ENV/src/django-grappelli/grappelli/models/fixtures/* --settings=settings
    

    copy | embed

    0 comments - tagged in  posted by nick on Mar 22, 2010 at 11:33 p.m. EDT
  • 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 %}
    

    copy | embed

    0 comments - tagged in  posted by vedran on Mar 10, 2010 at 11:16 a.m. EST
  • 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()
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Feb 26, 2010 at 6:39 p.m. EST
  • django
    hahaha
    

    copy | embed

    0 comments - tagged in  posted by zjm1126 on Jan 31, 2010 at 8:57 p.m. EST
  • 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):
         """
    

    copy | embed

    0 comments - tagged in  posted by muanis on Jan 26, 2010 at 1:38 p.m. EST
  • 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')
    

    copy | embed

    0 comments - tagged in  posted by palobo on Nov 28, 2009 at 5:22 p.m. EST
  • Dynamic redirection after login
    login_url = '%s?next=%s' % (reverse('acct_login'), reverse('jumplog_index'))
    return HttpResponseRedirect(login_url)
    

    copy | embed

    0 comments - tagged in  posted by shacker on Nov 24, 2009 at 2:33 a.m. EST
  • 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
    

    copy | embed

    0 comments - tagged in  posted by erincarter on Nov 16, 2009 at 3:23 p.m. EST
Sign up to create your own snipts, or login.