Change Django Auth User Meta

Posted: April 29th, 2010 | Author: Arif Harbott | Filed under: Django | Tags: , , | No Comments »

Sometimes it can be helpful to change the default behaviour of the Auth User model or other models built into Django.
One use case might be if you want to change the length of the username field in the Auth User model to allow for longer usernames (e.g. an email address).

There is a simple way to change the max length attribute:

from django.contrib.auth.models import User
User._meta.get_field_by_name('username')[0].max_length=75

Get/List model fields

Posted: February 22nd, 2010 | Author: Davo | Filed under: Django | Tags: , , , , , | No Comments »

It is possible to get/list all of the fields for the given model, to do so you need to access the _meta attribute of the Model.
The following example demonstrates how to do it.


# in the models.py
class Car(models.Model)
    year = models.IntegerField()
    name = models.CharField(max_length=50)
    ...

    def get_fields(self):
        # make a list of field/values.
        return [(field, field.value_to_string(self)) for field in Car._meta.fields]

Now that we implemented the get_fields function for our Car model, we can use this in the template…

# your template file...
# I assume that the variable 'car' is an instance of Car object.
{% for field, value in car.get_fields %}
    {{ field }} : {{ value }}
{% endfor %}