Problem with Django and Monkey

I recently started experimenting with Django for some web applications in my free time. When developing a data model for one, I came across the dilemma of using inheritance to define a website user or using a method known as a monkey patch, with the User class already provided by the framework.

I tried to add a field with (after defining all my models etc. without errors, according to python manage.py validate ):

User.add_to_class('location', models.CharField(max_length=250,blank=True))

and executed the syncdb . However, I keep getting this error

OperationalError: no such column: auth_user.location

Whether I am in the administrative view of the site or in the manage.py shell. There should be an extra step that I am missing, but there seems to be limited documentation on the whole technique of patch monkeys. Therefore, I ask you for help before resorting to inheritance. Any code, tips or pointers to additional documentation, of course, are welcome.

Thanks in advance.

PS. I know this technique is ugly and probably not recommended .;)

+4
source share
5 answers

When you add a field to any model, even if you do it in an β€œofficial” way, you need to transfer the database - Django does not do this for you. Clear the table and run ./manage.py syncdb again.

You might want to explore one of the migration infrastructures, such as south , that will manage this for you.

+7
source

There is an alternative to both approaches, which is to simply use a linked profile model . It is also a well-documented, highly recommended approach. Perhaps the reason the add_to_class method is not well documented is because it is clearly discouraged (for good reason).

+13
source

The Djangos framework uses metaclasses to initialize tables. This means that you cannot patch monkeys in new columns unless you reinitialize a class that I'm not sure is even possible. (May be).

See The difference between the returned modified class and the use of type () for more information.

0
source

I assume that you might have problems as to where your monkeypatch is defined. I think django syncdb only creates data tables from a "clean" auth application, so your model will be without a "location", and then your patch site will look for the field.

Probably a less painful way to add more information to user profiles is described in Django docs .

0
source

All Articles