I’m developing Django application, and I have following error
'Category' object has no attribute '_state'
My models are
class Blog(models.Model):
BlogMeta = models.CharField(max_length=200)
BlogTitle = models.CharField(max_length=100)
BlogContent = models.TextField()
BlogCategory = models.CharField(max_length=300)
BlogTags = models.CharField(max_length=300)
BlogDate = models.DateField()
def __unicode__(self):
return self.BlogTitle
def save(self):
self.BlogDate = datetime.datetime.now()
Categorylist = re.findall(r'\w+',self.BlogCategory)
TagList = re.findall(r'\w+', self.BlogTags)
#Get already existing tags and category
dbCategoryList = Category.objects.all()
dbTagsList = Tags.objects.all()
clisflag = False
tlisflag = False
#check if categories and tags in new blog exists previously or not.
for clis in Categorylist:
for dbclis in dbCategoryList:
if (clis == dbclis.CategoryName):
clisflag = True
break
else:
continue
if not clisflag:
createCategory = Category(clis)
createCategory.save()
clisflag = False
for tlis in TagList:
for dbtlis in dbTagsList:
if(tlis == dbtlis.TagName):
tlisflag = True
break
else:
continue
if not tlisflag:
createTag = Tags(tlis)
createTag.save()
tlisflag = False
class Tags(models.Model):
TagName = models.CharField(max_length=20)
TagDesc = models.TextField(null=True)
def __unicode__(self):
return self.TagName
def __init__(self,name):
self.TagName = name
self.TagDesc = ""
class Category(models.Model):
CategoryName = models.CharField(max_length=20)
CategoryDesc = models.TextField(null=True)
def __unicode__(self):
return self.CategoryName
def __init__(self, name):
self.CategoryName = name
self.CategoryDesc = ""
In a new blog post, the categories are taken as comma separated value, and if a new category is encountered it is added to the database.
Similarly for Tags.
I am not clear about this _state thing, could you please point me in the right direction.
Thanks a lot!
You’re not running
Model.__init__. You must do so.At the very least, you need to have a line like
super(Category, self).__init__()insideCategory.__init__.In practice, you have far more important design problems. You should not include the class name in attributes; it should be
Category.name, notCategory.CategoryName.Category.__init__should use keyword arguments, not its own special arguments. The description should haveblank=Trueinstead ofnull=True. You don’t needCategory.__init__.Here is a slightly tidier version of what you’re doing:
This is still ugly, though. Firstly and most importantly,
tagsandcategory(renamed tocategories) should be relations, not plain text.