Disciples
Disciples

Reputation: 703

How to display Foreign Key's choices in django-admin?

I have small problem related to django-admin panel. I have 2 models:

from django.db import models

class Subject(models.Model):
    subject = models.CharField(max_length=30, choices=[('P', 'Personal'), ('W', 'Work')])

    def __str__(self):
        return self.subject

class BlogPost(models.Model):
    id = models.AutoField(unique=True, primary_key=True)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
    text = models.TextField(null=False)
    pic = models.ImageField(upload_to='static/img/', default='static/img/no-image.png')
    date = models.DateTimeField()

    def __str__(self):
        return self.subject

But in admin panel whenever I try to create blog post, dropdown menu doesn't show any of subject's choices. Do I need to edit admin render function ?

Upvotes: 2

Views: 939

Answers (1)

Robert Foxa
Robert Foxa

Reputation: 91

By the way you have done it you have to first add the subjects themselves so they can appear in your foreign key choices. you could have the same results by:

class BlogPost(models.Model):
    id = models.AutoField(unique=True, primary_key=True)
    subject = models.CharField(max_length=30, choices=[('P', 'Personal'), ('W', 'Work')])

    def __str__(self):
        return self.subject

What do you want the ForeignKey for?

Upvotes: 2

Related Questions