Django mptt, category and subcategory system - Category has no field named 'parent'
-
01-07-2021 - |
سؤال
I would like created category and subcategory system using django mptt. My try:
from django.db import models
import mptt
class Category(models.Model):
name = models.CharField(max_length=255)
category = models.ForeignKey('self', null=True, blank=True, related_name='children')
mptt.register(Category, order_insertion_by=['name'])
class Post(models.Model):
title = models.CharField(max_length=255)
text = models.TextField()
category = models.ManyToManyField(Category)
My admin.py
from django.contrib import admin
from xxxx.xxx.models import *
from mptt.admin import MPTTModelAdmin
admin.site.register(Category, MPTTModelAdmin)
admin.site.register(Post)
My error:
Category has no field named 'parent'
المحلول
Django-mptt requires field with name parent with ForeignKey('self')
http://django-mptt.github.com/django-mptt/models.html#setting-up-a-django-model-for-mptt
You can overwrite that with:
class Category(models.Model):
name = models.CharField(max_length=255)
category = models.ForeignKey('self', null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by=['name']
parent_attr = 'category'
لا تنتمي إلى StackOverflow