You could tell Django to designate the 'code' field as the primary
key, which will automatically make it unique. Any forms will then be
forced to identify by the code, rather than some numeric id:
class Country(models.Model):
code = models.CharField(max_length=5, primary_key=True)
name = models.CharField(max_length=100, unique=True)
Hope that helps! There is another way to do it as well, but I opted
to keep it simple.
Tim
On Nov 26, 10:28 am, jul <[email protected]> wrote:
> hi,
>
> I'm generating, using ModelForm, a form from a Restaurant model, which
> has a Country field.
> Country has a 'code' and a 'name' fields.
> When the form is created in my template, the values of the select
> options are the Country ids. How can I replace them by the Country
> 'code' values. Is it possible to choose which field is used as the
> value by overriding the Country field in the ModelForm?
>
> thanks
>
> I have that:
>
> <label for="id_country">Country:</label> <select name="country"
> id="id_country">
> <option value="" selected="selected">---------</option>
> <option value="1">Andorra</option>
> <option value="2">United Arab Emirates</option>
> <option value="3">Afghanistan</option>
>
> and I want that:
>
> <label for="id_country">Country:</label> <select name="country"
> id="id_country">
> <option value="" selected="selected">---------</option>
> <option value="AD">Andorra</option>
> <option value="AE">United Arab Emirates</option>
> <option value="AF">Afghanistan</option>
>
> Models and ModelForm:
>
> class Country(models.Model):
> code = models.CharField(max_length=5, unique=True)
> name = models.CharField(max_length=100, unique=True)
>
> class Meta:
> verbose_name_plural = 'Countries'
>
> def __unicode__(self):
> return self.name
>
> class Restaurant(models.Model):
>
> name = models.CharField(max_length=100)
> country=models.ForeignKey(Country)
> city=models.ForeignKey(City)
> street=models.CharField(max_length=100)
> street_number=models.PositiveSmallIntegerField()
> phone_number=models.CharField(max_length=16, blank=True,
> null=True)
> price_range=models.PositiveSmallIntegerField(blank=True,
> null=True)
> category=models.ManyToManyField(Category, blank=True,
> null=True)
> tag=models.ManyToManyField(Tag, blank=True, null=True)
> slug = models.SlugField(unique=True)
>
> def get_absolute_url(self):
> return "/restaurant/%s/" % self.slug
>
> def __unicode__(self):
> return self.name
>
> def save(self):
> self.slug = slugify(self.name)
> super(Restaurant, self).save()
>
> class AddRestaurantForm(ModelForm):
>
> class Meta:
> model = Restaurant
> exclude = ('slug')
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.