snippets with tag 'django'

Shell : Perfect django .bat dev startup scriptCréez un fichier run.bat qu'il vous suffira de double cliquer pour lancer Django dans une boucle 'infinie'. Faites Ctrl+C pour relancer le serveur si besoin. (uniquement pour le serveur de dev)
@ECHO OFF

SET PORT=9000

:BEGIN
cd %~dp0
c:\python25\python.exe manage.py runserver 192.168.1.31:%PORT%
GOTO BEGIN
 
tags : system, django, bat, windows

Python : dynamic user profile accesUseful to filter profiles dynamically and in a generic way. thanx to mattcc@#django for ideas
from django.db.models import get_model
profile_class = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
jabber_user = profile_class.objects.filter(jabber !='')
tags : python, django

Django : automatic and unique slug fieldOverride your model save method to auto create an unique slug id. Useful for SEO. This method ensure the slug is unique using a regexp.
#!/usr/bin/python
 
from django.db import models, IntegrityError
import re
from django.template.defaultfilters import slugify
   
class MyModel(models.Model):

    title= models.CharField(max_length=50)
    slug = models.SlugField(blank = True, unique=True)

    def save(self):
        # auto fill the slug field
        if not self.slug:
            self.slug = slugify(self.title) 
        while True:
            try:
                super(MyModel, self).save()
            except IntegrityError:
                matches = re.match(r'^(.*)-(\d+)$', self.slug)
                if match_obj:
                    current = int(matches .group(2)) + 1
                    self.slug = matches .group(1) + '-' + str(current)
                else:
                    self.slug += '-2'
            else:
                break
tags : python, django, regexp

Django : DictCursor for raw sql using djangothis has been removed from django trunk because of unused, but maybe useful.
# inspired from old django code
# mimics MySQLdb.cursors.DictCursor behaviour

def dictfetchall(cursor): 
    "Returns all rows from a cursor as a dict" 
    desc = cursor.description 
    return [dict(zip([col[0] for col in desc], row))   for row in cursor.fetchall()]
tags : python, django, MySQL

Django : cookieless Django authentificationThis allows you to auth an user without any cookie, using a single POST parameter. this is especially useful for using with swfupload that cannot send cookies. Ideally, use this inside a decorator.
#!/usr/bin/python

def authFromSessionid(request):
    from django.shortcuts import get_object_or_404
    from django.contrib.sessions.models import Session
    session = get_object_or_404(Session, session_key=request.POST.get('sessionid'))
    session_data = session.get_decoded()
    user = get_object_or_404(User, pk = session_data['_auth_user_id'])
    request.user = user
tags : python, django

Django : Use your django project outside djangoThis is how to use your django models and data outside your web project. For example this can be used to create some cron jobs.
#!/usr/bin/python

from django.core.management import setup_environ
import settings
setup_environ(settings)

# do your stuff
tags : python, system, django

Django : Iterations sur un dictionnaire dans un template djangoSimple mais utile :)
{% for key,value in settings.items %}
        var SESSION_{{ key }} = "{{ value }}";
{% endfor %}
tags : python, django

SQL : Django+MySQL collation problems
ALTER DATABASE `mydbname` DEFAULT CHARACTER SET utf8 COLLATE 'utf8_unicode_ci';
tags : django, MySQL

Django : Autodetect project pathdont hardcode your paths !
# add this to your settings.py 
# BASE_DIR is your main project path

BASE_DIR = os.path.abspath(os.path.split(__file__)[0])
tags : python, django

all tags : python, system, vlc, video, apache, proxy, linux, django, MySQL, .NET, XML, XSL, regexp, bat, windows, bash, git

back to snippets home
site réalisé et hébergé par revolunet © 2009 - informations légales