views:

45

answers:

3

How can one define a dynamic initial value on a foreign key field?

With the code:

from django.db import models
from django.conf import settings
from django.contrib.sites.models import Site

class Example(models.Model):
    site = models.ForeignKey(Site, initial=settings.SITE_ID)

I've the following error:

site = models.ForeignKey(Site, initial=settings.SITE_ID)
Field.__init__(self, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'initial'

I also tried with:

class Example(models.Model):
    site = models.ForeignKey(Site, initial=Site.objects.get(id=settings.SITE_ID))

Thanks in advance

+1  A: 

Override the save() method of the model and check if the field's value is None.

Ignacio Vazquez-Abrams
Thanks. It could do the job but I want to display a default value in the form.
Pascal Polleunus
A: 

If I understand you right about the dynamic part, this is related to a Django foreign key FAQ, and James Bennett's Django tips: auto-populated fields (see The Holy Grail subhead :-).

Dave Everitt
Thanks but I don't want it to be automatically populated, I want users to be able to select another value than the default one.
Pascal Polleunus
+1  A: 

Model fields don't take an "initial" parameter, they take "default".

Daniel Roseman
Right! While looking around, I started with Model.default and ended in Field.initial, and I mixed them up.My problem was actually elsewhere but thanks anyway you helped me to find the solution.It seems one cannot define a dynamic default value in a new model then do a syncdb. So I had to remove the default param, do the syncdb, then add the default in the model.
Pascal Polleunus