使用 python 代码创建集合 [英] create collection with python code

查看:22
本文介绍了使用 python 代码创建集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个模型,允许 Wagtail 管理站点中的用户选择图像目录,在 CharField 中给出集合的名称,然后按下按钮,将创建具有给定名称的集合,然后来自给定目录的图像将被保存到数据库中(以便它们在 CMS 中可用).图片的标题是文件名,标签是图片所在的目录名.

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.

我发现了另一篇关于如何使用代码将图像保存到数据库的帖子 (图像保存)但我在以编程方式创建集合时遇到问题.我在这里找到了这个代码(从这里)应该可以工作,但显然对我来说不是,当我执行 manage.py makemigrations 时,我收到此错误:

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

我需要在 add_child 中提供路径吗?它应该是什么路径?提前感谢您的任何帮助!

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')

推荐答案

问题在于您直接在 GalleryPage 的定义中运行代码:

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')

这将在每次加载 models.py 时运行 - 特别是 ./manage.py makemigrations./manage.py migrate 命令需要加载 models.py 以了解如何设置您的数据库.此时创建数据库对象自然会失败,因为数据库还没有准备好......

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...

像这样运行测试代码的最佳位置可能是 ./manage.py shell 命令行,在那里您应该能够成功运行以下几行:

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')

这篇关于使用 python 代码创建集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆