Skip to content
Thierry Lam edited this page Aug 6, 2015 · 5 revisions
  1. Display non field errors, in the template:

     {{ form.non_field_errors }}
    
  2. Returning JSON from AJAX calls: Use double quotes instead of single quotes when returning the data:

     data = '{"output": "hello"}'
    
  3. Deleting and refreshing a cache manually

    • Delete the cache key form the shell:

        from django.core.cache import cache
        cache.delete('some_key')
      
    • Update the cache values again

    • Reload your apache server sudo /etc/init.d/apache2 reload

    • Displaying deprecated warnings

        python -Wd manage.py runserver 0.0.0.0:8000
      
  4. Using RequestFactory to construct fake request:

     from django.test import RequestFactory
    
     factory = RequestFactory()
     request = factory.get(
         '/home/', 
         REMOTE_ADDR='192.168.0.160', HTTP_X_CLIENTSIDE='123.456.789.20:32495 -> 192.168.0.160:443')
    
  5. If template caching is on(django.template.loaders.cached.Loader), disable it:

     TEMPLATE_LOADERS = (
         'django.template.loaders.filesystem.Loader',
         'django.template.loaders.app_directories.Loader',
     )
    

Running Django code from a script(sort of)

  1. Create a test.py script at the Django project level

  2. Run your django shell: python manage.py shell

  3. Enter the following:

     import test
     reload(test)
    
  4. From there on, apply changes to your test.py file and run reload(test) from the shell to see your latest changes

Accessing models from another Django project

Pre-conditions:

  1. You want to use existing models and data from another Django project
  2. You are using Django 1.2 +

This does not apply to shared Django apps. Re-using models from another Django project can be challenging if the model code is tightly couple to the other project and external dependencies. The best way to share models across multiple Django projects is to create an abstract model with the bare minimum of code. Make sure only Django libraries are imported:

# sharings/abstract_models.py
from django.db import models

class AbstractShare(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        abstract = True
        db_table = 'sharings_share'
# sharings/models.py
from django.db import models

from sharings.abstract_models import AbstractSharing

class Share(AbstractSharing):
    pass

db_table is the table name of the model that will actually be created.

AJAX

html

<input type="text" id="ajax-input" value="AJAX Input" />
<input type="button" id="update" value="Update" />
<div class="ajax-output"></div>

jQuery

$(document).ready(function() {
    $("#update").click(function() {
        $.getJSON("/ajax_call/",
            {
                ajax_input: $("#ajax-input").val(),
            },
            function(data) {
                $(".ajax-output").html(data.output);
            }
        );
    });
});

Django/Python

# urls.py
urlpatterns = patterns('myapp.views',
    url(r'^ajax_call/$', 'ajax_call', name='ajax-call')
)
# views.py
from django.utils import simplejson

def ajax_call(request):
    ajax_input = request.GET.get('ajax_input', '')
    if ajax_input:
        data = {'output': 'success'}
    else:
        data = {'output': 'failure'}
    return HttpResponse(simplejson.dumps(data), mimetype="application/javascript")

A test settings

Sometimes, there are development settings variable that are not compatible while running Django tests. This situation can be remedied by creating a test_settings.py file within your Django project directory:

# test_settings.py
from settings import *

CACHE_BACKEND = 'dummy:///'

The above is then invoked whenever a test is run:

python manage.py test my_app --settings=test_settings

Displaying links from ModelMultipleChoiceField items:

from django.utils.safestring import mark_safe

class MyForm(forms.Form):
    users = forms.ModelMultipleChoiceField(queryset=User.objects.all(), 
        widget=forms.CheckboxSelectMultiple())

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['users'].label_from_instance = lambda obj: mark_safe(
            '<a href="%s">%s</a>' % (obj.get_absolute_url(), obj)
        )
Clone this wiki locally