15

I have these two classes:

class Test(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User)
    groups = models.ManyToManyField(Group)

class TestSubjectSet(models.Model):
    id =  models.AutoField(primary_key=True)
    test = models.ForeignKey(Test)
    subject = models.ManyToManyField(Subject)

The TestSubjectSet form test list shows only string "test object".

2

3 Answers 3

30

You have to add __unicode__(self) or __str__(self) methods in your models class.

http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#django.db.models.Model.unicode

Sign up to request clarification or add additional context in comments.

1 Comment

__unicode__(self) did not work for me but __str__(self) did . Am using django 11
7

Had the same problem. Adding

def __str__(self):
    return self.user

solved the problem.

Comments

2

Sometimes you want to have different info returned from str function but Want to show some different info in the dropdown of admin. Then Above mentioned solution won't work.

You can do this by subclassing forms.ModelChoiceField like this.

class TestChoiceField(forms.ModelChoiceField):
 def label_from_instance(self, obj):
     return "Test: {}".format(obj.id)

You can then override formfield_for_foreignkey

def formfield_for_foreignkey(self, db_field, request, **kwargs):
  if db_field.name == 'test':
    return TestChoiceField(queryset=Test.objects.all())
  return super().formfield_for_foreignkey(db_field, request, **kwargs)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.