views:

24

answers:

1

If I have the following model in django;

class MyModel(models.Model):  
    name = models.CharField(max_length=50)
    fullname = models.CharField(max_length=100,default=name)

How do I make the fullname field default to name? As it is right now, the fullname defaults to the string representation of the name CharField.

Example:

new MyModel(name='joel')

would yield 'joel' as both name and fullname, whereas

new MyModel(name='joel',fullname='joel karlsson')

would yield different name and fullname.

+2  A: 

I wonder if you're better off doing this via a method on your model:

class MyModel(models.Model):  
    name = models.CharField(max_length=50)
    fullname = models.CharField(max_length=100)

    def display_name(self):
        if self.fullname:
            return self.fullname
        return self.name

Perhaps, instead of display_name this should be your __unicode__ method.

If you really want to do what you've asked though, then you can't do this using the default - use the clean method on your form instead (or your model, if you're using new-fangled model validation (available since Django 1.2).

Something like this (for model validation):

class MyModel(models.Model):
    name = models.CharField(max_length=50)
    fullname = models.CharField(max_length=100,default=name)

    def clean(self):
      self.fullname=name

Or like this (for form validation):

class MyModelForm(ModelForm):
    class Meta:
       model = MyModel

    def clean(self):
        cleaned_data = self.cleaned_data
        cleaned_data['fullname'] = cleaned_data['name']
        return cleaned_data
Dominic Rodger
+1. This is how I would do it.
Manoj Govindan
Why didn't I think of using a method... Thank you for a thorough answer ;)
Joel