create collection with python code

流过昼夜 提交于 2019-12-08 04:30:07

问题


i would like to make a model that will allow the user in the Wagtail admin site to choose a directory of images give the name of the collection in a CharField and upon a button press a collection with the given name would be created, then the images from a the given directory would then be saved to the database (so that they are avaialable in the CMS). The title of the image would be it's filename, while it's tag would be the directory name where the image is found.

I found another post on how to save Images to the database with code (image saving) but I have a problem creating collections programatically. I found here this code (from here) should work, but apparently for me it doesn't, when I do manage.py makemigrations, I get this error:

django.db.utils.IntegrityError: UNIQUE constraint failed: wagtailcore_collection.path

Do I need to provide the path in add_child? What path is it supposed to be? Thanks for any help in advance!

root_coll = Collection.get_first_root_node()
root_coll.add_child(name='testcoll')

回答1:


The problem is that you're running the code directly within the definition of GalleryPage:

class GalleryPage(Page):
    # test
    root_coll = Collection.get_first_root_node()
    root_coll.add_child(name='testcoll')

This will run every time models.py is loaded - and in particular, the ./manage.py makemigrations and ./manage.py migrate commands need to load models.py in order to find out how to set your database up. Creating database objects is naturally going to fail at that point, because the database isn't ready yet...

The best place to run test code like this is probably the ./manage.py shell command line, where you should be able to run the following lines successfully:

from wagtail.wagtailcore.models import Collection
root_coll = Collection.get_first_root_node()
root_coll.add_child(name='testcoll')


来源:https://stackoverflow.com/questions/43178845/create-collection-with-python-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!