Is it possible to override a wagtail.hooks.register function with a custom function?
Is it possible to override a wagtail @hooks.register
function with a custom function or to de-register a function all together?
One example of what I would like to achieve is editing the register_styleguide_menu_item
function in wagtail/contrib/styleguide/wagtail_hooks.py
so that the style guide is only shown to superusers.
For example; I would like to override the current function:
@hooks.register("register_settings_menu_item")
def register_styleguide_menu_item():
return MenuItem(
_("Styleguide"), reverse("wagtailstyleguide"), icon_name="image", order=1000
)
with this:
@hooks.register("register_settings_menu_item")
def register_styleguide_menu_item():
return AdminOnlyMenuItem(
_("Styleguide"), reverse("wagtailstyleguide"), icon_name="image", order=1000
)
(note the change from MenuItem to AdminOnlyMenuItem on the third line)
The docs for wagtail hooks are available at https://docs.wagtail.org/en/stable/reference/hooks.html but it doesn't cover this scenario.
Is there a mechanism to achieve this?
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Upload file from html when block public access is true
I am using
django-s3direct
to file uploadhttps://github.com/bradleyg/django-s3direct
Using IAM role setting because I upload the file from the server on ECS container.
Now I set the
blockPublicAccess
ofS3
false.When uploading images from html, there comes error.
https://s3.ap-northeast-1.amazonaws.com/static-resource-v/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg?uploads (403 (Forbidden) ) initiate error: static-resource-v/line-assets/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403
OK, it is understandable.
Browser try to access the for initiation.
However there is any way to upload file from browser when blockPublicAccess is true??
-
Test a decorated function in Python
I have a python function which is decorated.
@retry_if_access_token_expired(app_id) def add_something( self, *, argument1, argument1 = None, ): """adding something"""
I've written tests for the given as below.
@patch("other inside function to mock") @patch("other insdie function to mock 2") def test_add_something( self, mock_1, mock_2 ): """ some logic to test the add something method """
But I am getting this error that says add_somehthing takes 1 positional argument.
TypeError: add_something() takes 1 positional argument but 3 were given
-
how to pass null value to just one specific key of the one object using same DRF serializer
I'm just passing the same object 2 times in the same serializer but I want to pass key: "retweet": null in one object and in another object I want to pass some values like some many-to-many field values because key "retweet" is many-to-many field and having data
Thanks in advance!
-
Django (Wagtail) template not recognizing page type for if condition
On my wagtail blog, I have a simple model that will be the index page listing different articles, defined in my models.py as:
class ArticleIndex(Page): description = models.CharField(max_length=255, blank=True,) content_panels = Page.content_panels + [FieldPanel("description", classname="full")]
I have some template tags setup to show categories and tags in the sidebar, which should only activate on the index page, not actual article pages. I have this setup thusly:
{% if article_index %} {% categories_list %} {% tags_list %} {% endif %}
If I remove the if condition, everything displays as I want, so I know it is not an issue with the template tags.
I don't understand why
{% if article_index %}
is failing, as that's what the page type is.How can I print out what the actual page type is to see where the discrepancy is, or to see why the if condition is failing?
-
Wagtail panel for self-referential many to many relationships with a through model
I am busy making something like a knowledge graph in wagtail.
CurriculumContentItem
is a node on that graph. It has a many-to-many relationship with itself, and the through model has important fields.I'm struggling to get this to be usable in the admin page. Please see the inline comments:
class ContentItemOrder(models.Model): post = models.ForeignKey( "CurriculumContentItem", on_delete=models.PROTECT, related_name="pre_ordered_content" ) pre = models.ForeignKey( "CurriculumContentItem", on_delete=models.PROTECT, related_name="post_ordered_content" ) hard_requirement = models.BooleanField(default=True) class CurriculumContentItem(Page): body = RichTextField(blank=True) prerequisites = models.ManyToManyField( "CurriculumContentItem", related_name="unlocks", through="ContentItemOrder", symmetrical=False, ) content_panels = Page.content_panels + [ # FieldPanel("prerequisites") # FieldPanel just lets me select CurriculumContentItems, but I need to access fields in the through model # InlinePanel("prerequisites"), # This causes a recursion error FieldPanel('body', classname="full collapsible"), ]
If I wanted to do this in the normal Django admin I would make use of an inlines to specify prerequisites. Something like:
class ContentItemOrderPostAdmin(admin.TabularInline): model = models.ContentItem.prerequisites.through fk_name = "post" class ContentItemOrderPreAdmin(admin.TabularInline): model = models.ContentItem.unlocks.through fk_name = "pre"
Is there a similar mechanism in Wagtail?
It looks like I need to create a custom Panel for this.
-
Detect Django rest API conditions for accepting data before submitting
I've an API end point that accepts multiple choices to select special situations in a person page, like: disabilities or chronic disease. Django rest framework requires a list and gives this error when I send other type like string.
"special_situation":["Expected a list of items but got type \"str\"."]
However when I check the options of the endpoint I don't get an indication of that requirement:
HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "name": "Special Situation List", "description": "API endpoint that allows special situations to be viewed or edited.", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "url": { "type": "field", "required": false, "read_only": true, "label": "Url" }, "name": { "type": "string", "required": true, "read_only": false, "label": "Name", "max_length": 50 } } } }
I'm using
HyperlinkedModelSerializer
and endpoint is called at:http://127.0.0.1:8000/myapi/person/
and
http://127.0.0.1:8000/myapi/special_situation/
The end point is linked from
person
endpoint where I'm sending values based on the options ofspecial_situation
, the options forperson
end point also doesn't show the list requirement:"special_situation": { "type": "field", "required": false, "read_only": false, "label": "Special situation" }
In the person module I've:
special_situation = ParentalManyToManyField('needy.SpecialSituation', blank=True, verbose_name='special situation')
And for
SpecialSituation
:@register_snippet class SpecialSituation(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) panels = [ FieldPanel('name'), ] def __str__(self): return self.name class Meta: verbose_name_plural = 'special situations'
I thought the
"type": "field"
indicates a list it self but it's not acceptable in other endpoints without multiple choices. like in thecharity
end point."charity":["Incorrect type. Expected URL string, received list."]
full source code is availbe at: https://gitlab.com/uak/needy/-/tree/api_development
so the issue is that there is no indication that this end point requires a list except in the error message. I would like to be able to detect accepted type before I submit data to be able to dynamically construct a form in my GUI app.
I know I can manually detect the field name and create a list but would like a dynamic/automated without hard coding fields with different requirements.
-
Add a custom link/model to wagtail's admin sub-menu
Wagtail documentation explains how to:
Let our model be
CustomManager
and its admin url be/admin/custom_manager/
.Using a hook, we can add a link to our page on to the first level of the admin menu:
@hooks.register('register_admin_menu_item') def register_edit_menu_item(): return MenuItem( 'Custom Manager', '/admin/custom_manager/', classnames='icon icon-folder-inverse', order=1000)
But how can we add this link to a sub-menu/group, when our model is not a wagtail model?