How to create streamblocks and add them to stream field programatically?
Closed this issue · 2 comments
adrenaline681 commented
I have an Article model looking something like this:
class Article(Model):
title = models.CharField(max_length=255)
content = StreamField(
verbose_name='Blocks',
model_list=[Text, Header, SubHeader, ImageSingle, ImageDouble, Video, InfoBox, MultiUse],
)
Now I want to programmatically create the streamfields and add them to the article
# Create article
article = Article()
article.title = 'This is my title'
#Create text blocks
text1 = RichText(text='<p>This is the first block of text<p>')
text2 = RichText(text='<p>This is the second block of text<p>')
text1.save()
text2.save()
# Add text to article
article.content = [text1, text2] #This doesn't work
article.content.add(text1) # This doesn't work either
article.content.add(text2) # This doesn't work either
# Save article to database
article.save()
How can I programmatically add the streamblocks to the article?
raagin commented
I made a method add
. You can try it in version 2.1.2.
Like this:
article.content.add(text1)
article.save()
For "as_list" model:
article.content.add([im1, im2])
adrenaline681 commented
Thanks, I tested it and seems to be working correctly. BTW I think there is a typo when you try to delete a block in the admin, it says "Are you shure you want to", It should be "Are you sure". Cheers!