Rajesh Dhawan wrote: > >> My model : >> >> class phonenumber(models.Model): >> location_type = models.ForeignKey(location_type) >> location_description = models.CharField(max_length=50, blank=True) >> >> def __unicode__(self): >> if self.location_description: >> retval = self.location_description + ' - ' >> else: >> retval = self.location_type + ' - ' >> return retval >> >> class Meta: >> app_label = 'contacts' >> >> I get an error saying : >> TypeError at /contacts/phonenumber/ >> unsupported operand type(s) for +: 'location_type' and 'str' >> >> How do I get the location_type __unicode__ for the fk? >> > > Emily's suggestion of renaming your ForeignKey to LocationType is a > good one. If you want to follow more well-defined conventions while > coding in Python look at PEP 8 here: http://www.python.org/dev/peps/pep-0008/ > > Adding __unicode__ or __str__ methods to your location_type class is > not sufficient for the above to work because the + operator can not be > used in this way where location_type is not a string. > > Here are ways that would work: > > retval = unicode(self.location_type) + ' - ' > retval = '%s-' % self.location_type > > For these two snippets to work 'correctly', you should define > __unicode__ on your location_type model class. The two snippets above > will still work without this method, but you will get Python's > internal representation of location_type. > > For a better understanding of this look at __repr__, __str__, and > __unicode__ here: http://docs.python.org/ref/customization.html > > Thanks everybody, the following worked: retval = self.location_type.__unicode__() + ' - '
Emily & Rajesh: This is my first django project and I was eager to have it up and running. Sure I'll read up on coding conventions and change my code accordingly. Thanks once again Regards Ganesh --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com 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 -~----------~----~----~----~------~----~------~--~---