Django

Django is a high-level Python web framework. It has very good documentation at www.djangoproject.com.

Gotchas

Admin

Fomfield For ForeignKey

The formfield_for_foreignkey method on a ModelAdmin allows you to override the default formfield for a foreign key field. For example, to return a subset of objects for this foreign key field based on the user:

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Commands

Reset Password using shell

  1. python manage.py shell
  2. from django.contrib.auth.models import User
  3. u=User.objects.get(username__exact='[userid]')
  4. u.set_password('[new_password]');
  5. u.save()

Forms

Models

Meta

Natural Keys

A natural key is a tuple of values that can be used to uniquely identify an object instance without using the primary key value. They can be used to serialise data into fixtures to avoid the problem of needing foreign-keyed data to always have the same primary key.

Add a get_by_natural_key function to the model's manager which gets and returns the unique row which matches its parameters. Add a natural_key function to the model to return the tuple of data which uniquely identifies a model instance.

Serialise the data using dumpdata by adding a --natural parameter. python manage.py dumpdata --natural --indent 4 cm > [app]/fixtures/initial_data.json.

Settings

Templates

Iterate through field choices

{% for id, label in form.banana.field.choices %}
    {{ id }}': '{{ label }}'{% if forloop.last %}{% else %},{% endif %}
{% endfor %}

Views