How to access note data before anki create cards

I’m trying to create an add-on that automatically fill some fields in specific note types before anki start to create the cards.

You can probably automatically fill in note fields in the Add screen using the editor_did_load_note and add_cards_did_change_note_type hooks. See anki/genhooks_gui.py at main · ankitects/anki · GitHub

1 Like

Cool, this solves one problem, but how do I access the data? I know it’s something.editor but can’t find it

Here is a working example (using add_cards_did_init instead of editor_did_load_note because I found the latter can cause infinite loops here because of the editor.loadNoteKeepingFocus() call):

from anki.models import NoteType
from aqt import dialogs, gui_hooks
from aqt.addcards import AddCards
from aqt.editor import Editor


def is_target_notetype(notetype: NoteType) -> bool:
    return True

def fill_fields(editor: Editor, notetype: NoteType) -> None:
    if is_target_notetype(notetype):
        editor.note.fields[0] = "test"
        # editor.note["Front"] = "test"
        editor.loadNoteKeepingFocus()

def on_notetype_changed(old: NoteType, new: NoteType) -> None:
    addcards: AddCards = dialogs.open("AddCards")
    fill_fields(addcards.editor, new)


def on_add_cards_did_init(addcards: AddCards) -> None:
    fill_fields(addcards.editor, addcards.editor.note.note_type())

gui_hooks.add_cards_did_change_note_type.append(on_notetype_changed)
gui_hooks.add_cards_did_init.append(on_add_cards_did_init)

2 Likes

Perfect! Thank you! I’m gonna test

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.