Axwack
Axwack

Reputation: 569

Django Model Form Many to Many field is not displaying value

I have a many to many field and a foreign key field on a model form. It appears to be making the right query but the result are Objects and not the values of the object.

Do I need to overwrite the queryset using a VALUES_LIST method?

forms.py

    class Meta:
    model = AccountParameters
    fields =['acctFilterName', 'excludeClassification', 'tradingCash',]
    #exclude = ['acctFilterName']
    labels = {
        'acctFilterName': _('Account Filters:'),
        'excludeClassification': _('Exclude Classifications: '),
        'tradingCash':_('Remove accounts whose trading cash < % of AUM: ')
    }

models.py

class AccountParameters(models.Model):
acctFilterName = models.ForeignKey(AccountFilters)
excludeClassification = models.ManyToManyField(ClassificationNames)
tradingCash = models.FloatField()

Screenshot of multiselect

Upvotes: 2

Views: 1307

Answers (1)

Louis Barranqueiro
Louis Barranqueiro

Reputation: 10228

You have to add a method to represent your object with a string :

If you are using python 2, use __unicode__ and on python 3 use : __str__ .

E.g (with python 2) :

class AccountFilters(models.Model):
    name = models.CharField(max_length=255)
    # other attributes

    def __unicode__(self):
        return self.name

class AccountParameters(models.Model):
    acctFilterName = models.ForeignKey(AccountFilters)
    excludeClassification = models.ManyToManyField(ClassificationNames)
    tradingCash = models.FloatField()

    def __unicode__(self):
        return self.acctFilterName.name

E.g (with python 3) :

class AccountFilters(models.Model):
    name = models.CharField(max_length=255)
    # other attributes

    def __str__(self):
        return self.name

class AccountParameters(models.Model):
    acctFilterName = models.ForeignKey(AccountFilters)
    excludeClassification = models.ManyToManyField(ClassificationNames)
    tradingCash = models.FloatField()

    def __str__(self):
        return self.acctFilterName.name

Upvotes: 1

Related Questions