3👍
✅
Your code seems correct to me. I also worked on a generic class for my project and it was similar to this one. One remark, when you get a block, you should do some type checking to retrieve the class data so, I recommend you to add a field to store its type. e.g:
class Block(models.Model):
title = models.CharField(max_length=50)
type = models.IntegerField()# 1 for text, 2 for email and 3 for url
#Make sure child classes have content defined!
#content = models.BooleanField(default=False)
owner = models.ForeignKey('User')
access = models.ManytoManyField('User', null=True)
links = models.ManytoManyField('self', null=True)
Then in your view:
def getblock(request, block, no):
if block.type == 1:
data = get_object_or_404(Block,id=no).text
elif block.type == 2:
data = get_object_or_404(Block,id=no).email
elif block.type == 3:
data = get_object_or_404(Block,id=no).url
return render_to_response('single.html',{'data':data})
You can access the subclasses with lower case representation of that child class. I think that will work nicely. Also I don’t get the dictionary type arguments you wrote and that gave a syntax error when I executed. Anyway, I also corrected some of the syntax errors, too.
👤Hgeg
Source:stackexchange.com