Showing posts with label django. Show all posts
Showing posts with label django. Show all posts

Tuesday, May 5, 2015

Django Classified App

Great and easy to use scaffolding template for you Classified app made using django
DCF - django classified app

Monday, April 20, 2015

django-compressor

Nice and easy way to minify your CSS and JS files in to one with compression options is to use great tools django-compressor

Just provide wrap you CSS or JS files into
{% compress <js/css> %} link to your files here
{% endcompress %}
And thats it!

Friday, January 9, 2015

django-constance

A Django app for storing dynamic settings in pluggable backends (Redis and Django model backend built in) with an integration with the Django admin app.

GitHub Repo

Tuesday, September 9, 2014

Must-have Django packages.

Excellent post by Alberto Granzotto about handy django packages all django developer must know

Thursday, September 4, 2014

Sorl-Thumbnails

Great project for using thumbnails for ImageField in django.
You need only upload images, and Sorl-Thumbnail create all needed sizes for you images when whey need in template.

TIPS: Use latest build from github:
pip install https://github.com/mariocesar/sorl-thumbnail/archive/master.zip


Monday, February 24, 2014

Using request.DELETE in django

If you want to access QueryDict parameters, when using request.method == 'DELETE' you can't access it via request.DELETE as when you use GET or POST.

Instead you should create that Dict yourself:

from django.http import QueryDict
<...>
def my_delete_api(request):
if request.method == 'DELETE':
data = QueryDict(request.body)
                key = data.get('key', None)


Wednesday, February 5, 2014

Django 1.7 on the way!

Soon new version of Django will arrive!
https://docs.djangoproject.com/en/dev/releases/1.7/

So if you have old python 2.6 - don't forget to update for 2.7!

So if you use Debian 6 squeeze, you need to update for wheezy!

You can follow that easy manual:
http://www.howtoforge.com/how-to-upgrade-debian-squeeze-to-wheezy

Tuesday, October 1, 2013

Django registration updates

Great project for easy handling user registration in django has updated recently (ok, not actually recently) for django 1.5 support.
If you still do what kind of stuff by hand - take a loot at that helpful project.
django-registration

Thursday, September 26, 2013

OSQA updates for latest Django version

Check out my fork of OSQA project on GitHub.
Now they work with latest Django version 1.5.

OSQA is Open Source Q&A system, created using python (Django), Jquery and other cool tools!

https://github.com/8c1/OSQA

Thursday, February 28, 2013

Django release 1.5 is now available!

Congratulation, version 1.5 of Django Web Framework is now have release status!

In case you have DeprecationWarning:

DeprecationWarning: You have no filters defined on the 'mail_admins' logging handler: adding implicit debug-false-only filter

Update you LOGGING settings for something like that:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}


Improvement of moving from SQLite to MySQL

I want to introduce improvement of my solution switching from SQLite to other DB engine maded by Rune Kaagaard.
Go to the github page.

Monday, November 26, 2012

Dealing with unicode user name in OSQA

OSQA is a pretty engine for creating Q&A site for in you community.

I use it for a couple of weeks and i'm very happy with it.
But some day ago i start receiving letter from my user in that they say that it is a bug on site, and user cannot fill additional field in user profile.
After investigation i found a bug.
The root of problem was unicode username.

Link for user settings contain slug field and look like:
url(r'^%s(?P<id>\d+)/(?P<slug>.*)/%s$' % (_('users/'), _('edit/')), app.users.edit_user, name='edit_user'),
and in actual form url it look like
<form name="" action="/users/1/admin/edit/" method="post">
but when you user have unicode user name it look like:
<form name="" action="/users/21//edit/" method="post">
and when user with unicode username try to submit form system do redirect 302 instead of saving data redirect them to correct url for editing (but url in form still same wrong).

i look to the template for edit preference page(forum\skins\default\templates\users\edit.html:36):

<form name="" action="{% url edit_user user.id user.username|slugify %}" method="post">

so template filter slugify does not work with unicode :(

So i created new one :)

in file forum\templatetags\extra_filters.py i add new tag

from django.utils.encoding import smart_unicode
from django.template.defaultfilters import slugify
@register.filter
def slug(value):
    return slugify(smart_unicode(value))
and use them instead |slugify 
i add 
{% load extra_filters %}
in top of template and change filter in form action link:
<form name="" action="{% url edit_user user.id user.username|slug %}" method="post">

And now my users are happy :)




Wednesday, October 24, 2012

Django admin select field limit, based on another ForeignKey fields

Let say you have models:

class CompanyInfo(models.Model):
    name = models.CharField('Company name',max_length=250)

class Staff(models.Model):
    company_name = models.ForeignKey(CompanyInfo)
    date = models.DateField()
    name = models.CharField('Name', max_length=30, )

class Relation(models.Model):
    company_name = models.ForeignKey(CompanyInfo)
    who = models.ForeignKey(Staff, related_name="who", blank=True)
    with_whom = models.ForeignKey(Staff, related_name="with_whom", blank=True)

And you want limit staff list in Relation form for only staff, who related for that company by field company_name.
This admin.py helps you solve that problem:

# -*- coding:utf-8 -*-
from models import Staff, Relation
from django.contrib import admin
from django import forms

class RelationForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(RelationForm, self).__init__(*args, **kwargs)
        qs = Staff.objects.filter(company_name = self.instance.company_name)
        self.fields['who'].queryset = qs
        self.fields['with_whom '].queryset = qs

class RelationAdmin(admin.ModelAdmin):
    form = RelationForm

admin.site.register(Relation, RelationAdmin)

Do you know, how do it for new entry? :)

Friday, October 19, 2012

[solved] Move django from SQLite to MySQL

When you start develop new site, you may run from little one with tiny database.
For django best start from sqlite and after some time, if you project begin grow you move to more serious database engine (MySQL, Postgre SQL etc).
Sadly, django does not have any ready tools to move from one to another database.
You may try

  • python ./manage.py dumpdata > data.json

and

  • python ./manage.py loaddata data.json

but unfortunately this doesn't work because of integrity errors...or many other issues

For move from one db to another i follow steps:
  1. Edit settings.py 
    1. add new database in DATABASES settings with 'slave' name like:
      DATABASES = {'default': {...}, 'slave': {...}}
      
    2. if you use apps like south - comment them for a while
  2. Create new db (django create only new file for sqlite database type)
  3. Create tables in new db
    1. python ./manage.py syncdb --database slave
    2. enable south and repeat 3.1
  4. Create file to_slave.py in main project directory:
    • from django.contrib.contenttypes.models import ContentType
      
      def run():
      
       def do(Table):
        if Table is not None:
         table_objects = Table.objects.all()
         for i in table_objects:
          i.save(using='slave')
       
       ContentType.objects.using('slave').all().delete()
      
       for i in ContentType.objects.all():
        do(i.model_class())
      
  5. If you have any kind of signals for you models - disable them before next step
  6. run 
    1. python ./manage.py shell and type command in shell
      1. from to_slave import run
      2. run()
  7. Make 'slave' default database in you project
  8. Done






Sunday, September 23, 2012

Check if field is changed before saving entry


When you save entry in Django, how to check, if a field is changed?
Here is simple solution:
class MyModel(models.Model):
    title = models.CharField(max_length=1)

    def save(self, *args, **kw):
        if self.pk is not None:
            orig = MyModel.objects.get(pk=self.pk)
            if orig.title != self.title:
                print 'title is changed'
        super(MyModel, self).save(*args, **kw)

Friday, July 6, 2012

[fixed] How to load initial data to you django app model


If you need to have some data in you django app when you distribute it to someone else you need to do following steps.
Suppose you have app named weather and a model in that app called City
  1. Create folder fixtures in weather directory
  2. run following comand form project main directory:
python manage.py dumpdata weather.City > "weather\fixtures\initial_data.json"
  1. Whats all
Next time you run:
python manage.py syncdb
you data will be loaded to you app model
Lean more about initial data on django official page 

Tuesday, June 26, 2012

[Fixed] multisite caching on django

When you work with multisite on django you need to do some chaching tricks for optimize perfomance of you sites. Typically you use cache middleware and have no problem for one site

    MIDDLEWARE_CLASSES = [
        'django.middleware.cache.UpdateCacheMiddleware',
        ...
        'django.middleware.cache.FetchFromCacheMiddleware'
    ]
But for many sites you can't use it from the box (otherwise you get equal page for east.mycorp.com/contact.html and west.mycorp.com/contact.html). Trick is simple, you need to do some changes in cache middleware, placed in path to you django installation>/django/middleware/cache.py You need overwrite two function:
  • get_cache_key
  • learn_cache_key
Becasuse basicly django use request.get_full_path() for build cache_key, and when you deal with multisite you get the same result for east.mycorp.com/contact.html and west.mycorp.com/contact.html. We change get_full_path to build_absolute_uri So we put function:
  • _generate_cache_header_key
  • _generate_cache_key
  • get_cache_key - unchanged
  • learn_cache_key - unchanged
from /django/utils/cache.py to our new code in cache.py:
from django.conf import settings
from django.core.cache import get_cache, DEFAULT_CACHE_ALIAS
from django.utils.cache import patch_response_headers, get_max_age, _i18n_cache_key_suffix
from django.utils.hashcompat import md5_constructor
from django.utils.encoding import iri_to_uri

import re
cc_delim_re = re.compile(r'\s*,\s*')

# custom function for Multisiting
def _generate_cache_header_key(key_prefix, request):
    """Returns a cache key for the header cache."""
    #path = md5_constructor(iri_to_uri(request.get_full_path()))
    path = md5_constructor(iri_to_uri(request.build_absolute_uri())) # patch using full path
    cache_key = 'views.decorators.cache.cache_header.%s.%s' % (
        key_prefix, path.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)

def _generate_cache_key(request, method, headerlist, key_prefix):
    """Returns a cache key from the headers given in the header list."""
    ctx = md5_constructor()
    for header in headerlist:
        value = request.META.get(header, None)
        if value is not None:
            ctx.update(value)
    #path = md5_constructor(iri_to_uri(request.get_full_path()))
    path = md5_constructor(iri_to_uri(request.build_absolute_uri()))
    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
        key_prefix, request.method, path.hexdigest(), ctx.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)

def get_cache_key(request, key_prefix=None, method='GET', cache=None):
    """
    Returns a cache key based on the request path and query. It can be used
    in the request phase because it pulls the list of headers to take into
    account from the global path registry and uses those to build a cache key
    to check against.

    If there is no headerlist stored, the page needs to be rebuilt, so this
    function returns None.
    """
    if key_prefix is None:
        key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
    cache_key = _generate_cache_header_key(key_prefix, request)
    if cache is None:
        cache = get_cache(settings.CACHE_MIDDLEWARE_ALIAS)
    headerlist = cache.get(cache_key, None)
    if headerlist is not None:
        return _generate_cache_key(request, method, headerlist, key_prefix)
    else:
        return None

def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
    """
    Learns what headers to take into account for some request path from the
    response object. It stores those headers in a global path registry so that
    later access to that path will know what headers to take into account
    without building the response object itself. The headers are named in the
    Vary header of the response, but we want to prevent response generation.

    The list of headers to use for cache key generation is stored in the same
    cache as the pages themselves. If the cache ages some data out of the
    cache, this just means that we have to build the response once to get at
    the Vary header and so at the list of headers to use for the cache key.
    """
    if key_prefix is None:
        key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
    if cache_timeout is None:
        cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
    cache_key = _generate_cache_header_key(key_prefix, request)
    if cache is None:
        cache = get_cache(settings.CACHE_MIDDLEWARE_ALIAS)
    if response.has_header('Vary'):
        headerlist = ['HTTP_'+header.upper().replace('-', '_')
                      for header in cc_delim_re.split(response['Vary'])]
        cache.set(cache_key, headerlist, cache_timeout)
        return _generate_cache_key(request, request.method, headerlist, key_prefix)
    else:
        # if there is no Vary header, we still need a cache key
        # for the request.get_full_path()
        cache.set(cache_key, [], cache_timeout)
        return _generate_cache_key(request, request.method, [], key_prefix)

And save it to the new folder SiteCache in your django project directory. Now add to settings.py:
MIDDLEWARE_CLASSES = (
    'SiteCache.cache.UpdateCacheMiddleware',
    ...
    'SiteCache.cache.FetchFromCacheMiddleware',
)
Congratulations, now request to cached page east.mycorp.com/contact.html and west.mycorp.com/contact.html return proper results!

Monday, June 25, 2012

How to entirely clear django cache

Some time you need for developer purposes entirely clear django cache, to do it use that simple code:
from django.core.cache import cache
cache.clear()