Adds a plugin to a placeholder and returns it. :param placeholder: Placeholder to add the plugin to :type placeholder: :class:`cms.models.placeholdermodel.Placeholder` instance :param plugin_type: What type of plugin to add :type plugin_type: str or :class:`cms.plugin_base.CMSP
(placeholder, plugin_type, language, position="last-child", target=None, **data)
| 393 | |
| 394 | @transaction.atomic |
| 395 | def add_plugin(placeholder, plugin_type, language, position="last-child", target=None, **data): |
| 396 | """ |
| 397 | Adds a plugin to a placeholder and returns it. |
| 398 | |
| 399 | :param placeholder: Placeholder to add the plugin to |
| 400 | :type placeholder: :class:`cms.models.placeholdermodel.Placeholder` instance |
| 401 | :param plugin_type: What type of plugin to add |
| 402 | :type plugin_type: str or :class:`cms.plugin_base.CMSPluginBase` sub-class, must be a valid plugin |
| 403 | :param str language: Language code for this plugin, must be in :setting:`django:LANGUAGES` |
| 404 | :param str position: Position to add this plugin to the placeholder. Allowed positions are ``"last-child"`` |
| 405 | (default), ``"first-child"``, ``"left"``, ``"right"``. |
| 406 | :param target: Parent plugin. Must be plugin instance |
| 407 | :param data: Data for the plugin type instance |
| 408 | """ |
| 409 | # validate placeholder |
| 410 | assert isinstance(placeholder, Placeholder) |
| 411 | |
| 412 | # validate and normalize plugin type |
| 413 | plugin_model, plugin_type = _verify_plugin_type(plugin_type) |
| 414 | |
| 415 | if target: |
| 416 | if position == "last-child": |
| 417 | new_pos = placeholder.get_next_plugin_position(language, parent=target, insert_order="last") |
| 418 | parent_id = target.pk |
| 419 | elif position == "first-child": |
| 420 | new_pos = placeholder.get_next_plugin_position(language, parent=target, insert_order="first") |
| 421 | parent_id = target.pk |
| 422 | elif position == "left": |
| 423 | new_pos = target.position |
| 424 | parent_id = target.parent_id |
| 425 | elif position == "right": |
| 426 | new_pos = target.position + 1 + target._get_descendants_count() |
| 427 | parent_id = target.parent_id |
| 428 | else: |
| 429 | raise Exception("position not supported: %s" % position) |
| 430 | else: |
| 431 | assert position in ("first-child", "last-child") |
| 432 | if position == "last-child": |
| 433 | new_pos = placeholder.get_next_plugin_position(language, insert_order="last") |
| 434 | else: |
| 435 | new_pos = 1 |
| 436 | parent_id = None |
| 437 | |
| 438 | plugin_base = CMSPlugin( |
| 439 | plugin_type=plugin_type, |
| 440 | placeholder=placeholder, |
| 441 | position=new_pos, |
| 442 | language=language, |
| 443 | parent_id=parent_id, |
| 444 | ) |
| 445 | plugin_base = placeholder.add_plugin(plugin_base) |
| 446 | plugin = plugin_model(**data) |
| 447 | plugin_base.set_base_attr(plugin) |
| 448 | plugin.save() |
| 449 | return plugin |
| 450 | |
| 451 | |
| 452 | def create_page_user( |