Django Model Form Many to Many field is not displaying value

巧了我就是萌 提交于 2020-01-07 09:05:32

问题


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()


回答1:


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


来源:https://stackoverflow.com/questions/33818717/django-model-form-many-to-many-field-is-not-displaying-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!