Code to create a card?

hi, can someone help me figure out how to add a new card in python? This only works sometimes, so it must be wrong.

from aqt import mw
model = mw.col.models.byName("cardTypeNameHere")
new_note = mw.col.newNote(model)
new_note.model()["did"] = mw.col.decks.id("deckNameHere")
new_note["fieldNameA"] = 'foo'
new_note["fieldNameB"] = 'bar'
mw.col.addNote(new_note)

I think this is not the correct way to specify the deck and card type of new_note.

Thanks for any help!

Try passing the deck ID to addNote instead:

from aqt import mw
model = mw.col.models.byName("cardTypeNameHere")
new_note = mw.col.newNote(model)
new_note["fieldNameA"] = 'foo'
new_note["fieldNameB"] = 'bar'
did = mw.col.decks.id("deckNameHere")
mw.col.addNote(new_note, did)

I’m catching an error on that 4th line

KeyError: 'fieldNameA'

and I’ve confirmed through the REPL that the line above it (new_note = mw.col.newNote(model)) is not creating a note of tpye “cardTypeNameHere”.

Instead, it is creating a note of whichever type I last created by hand through anki’s “Add” gui window.

In other words, when I press “Add” to create a new card by hand, whatever the card type is shown there, that’s the same card type that new_note = mw.col.newNote(model) creates in python

col.newNote() is deprecated and takes a boolean, not a notetype. Use col.new_note() which has the signature you expect.
I’d advise you to look at the source code or enable type hints.

ok just figured it out. Yeah I’m pretty new to OOP in general, and learning how to read this stuff.

For any future searchers, this (ugly) code works:

new_note = mw.col.new_note(mw.col.models.get(mw.col.models.id_for_name("cardTypeNameHere")))
new_note["fieldNameA"] = 'foo'
new_note["fieldNameB"] = 'bar'
did = mw.col.decks.id("deckNameHere")
mw.col.add_note(new_note, did)