Vio Vio - 2 months ago 15
Python Question

Django admin - Inline with choices from database

I need some basic help with the django admin site. What I basically want to do is to be able to populate an inline with choices from the database. For example consider the following models:

class Item(models.Model):
description = models.CharField(max_length=100)

class Category(models.Model):
name = models.CharField(max_length=100)
item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, blank=True)

And in I have the following setup:

class CategoryAdminForm(forms.ModelForm):
name = forms.ChoiceField(choices = category_service.get_all_categories())

class CategoryInline(admin.TabularInline):
model = Category
form = CategoryAdminForm

class ItemAdmin(admin.ModelAdmin):
inlines = [CategoryInline], ItemAdmin)

What I want to be able to do is to insert categories into db, and when I want to insert an item, the categories inline to be populated with categories from the db.

With the current setup it is not working. It says that category is not an iterable object. What am I missing here?


You should replace your ChoiceField with a ModelChoiceField. They allow you to specify a queryset to populate the choices.

category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label="(Nothing)")