Reputation: 1766
I use Django 1.11.10 and python 3.6; I have Category
model that has name
and parent
. Parent field links to itself. But when I create new Category
model, I want choose parent from already created categories that have no parents. So how to predefine this list?
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
parent = models.ForeignKey('self', null=True, blank=True)
------
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ['name', 'parent']
class CategoryAdmin(admin.ModelAdmin):
form = CategoryForm
admin.site.register(Category, CategoryAdmin)
Upvotes: 0
Views: 84
Reputation: 1061
I think you want a drop down in the form when the a accesses the front end.
You can add this to your form:
parent = forms.forms.ModelChoiceField(queryset= Category.objects.all(), required = True)
So the final form would look like:
class CategoryForm(forms.ModelForm):
parent = forms.forms.ModelChoiceField(queryset= Category.objects.all(), required = True)
class Meta:
model = Category
fields = ['name', 'parent']
Let me know if this is what you wanted!
Upvotes: 1