Use Groq to Add Entries to the Database:
- In Unit 4 you used your Groq API key to create an AI chatbot.
- Now we will use that same key to add entry records to our database.
- We will write a script that asks Groq to write 5 journal entries for each of our topics (Data_Types and Lists), and then saves each entry to db.sqlite3.
Create the populate_entries.py File:
- In VS Code, create a new file named populate_entries.py in your activity root folder (the same folder as manage.py).
- Copy and paste each code block below into populate_entries.py, in order, one after the other.
Step 1: Connect the Script to Django:
populate_entries.py
python
1import os
2import django
3
4# Tell Django where the project settings are, then start Django
5os.environ.setdefault("DJANGO_SETTINGS_MODULE", "code_journal.settings")
6django.setup()
7
8from groq import Groq
9from code_journals.models import Topic, Entry- Normally, manage.py sets up Django for us. Since we are running our own script, we have to do it ourselves.
- DJANGO_SETTINGS_MODULE tells Django to use the settings.py file inside the code_journal folder.
- django.setup() loads the project so we can work with the database.
Step 2: Add Your Groq API Key:
populate_entries.py
python
10# Your Groq API key
11api_key = "Paste your Groq API key here!"
12os.environ["GROQ_API_KEY"] = api_key
13
14# Create an instance of Groq
15groq = Groq()- Replace the text in the quotes on line 11 with your own Groq API key!!
Step 3: List the Topics:
populate_entries.py
python
16# The topics to add entries to
17topic_names = ["Data_Types", "Lists"]- topic_names is a list of the two topics we want to fill.
- Each name must match the topic exactly as it appears in the admin site (including capital letters and the underscore).
Step 4: Ask Groq for Entries and Save Them:
populate_entries.py
python
18# The instructions Groq follows for every entry
19system_prompt = (
20 "You are a student in a coding class who is learning Python "
21 "this semester. You keep a journal reflecting on what you're "
22 "learning in class. Vary how each entry starts, for example "
23 "with a question, a reaction, or the topic itself."
24)
25
26# For each topic, ask Groq for 5 entries and save each one
27for topic_name in topic_names:
28 topic = Topic.objects.get(text=topic_name)
29 user_prompt = (
30 "Write a 1 sentence journal entry about the Python topic "
31 f"{topic_name}."
32 )
33 messages = [
34 {
35 "role": "system",
36 "content": system_prompt,
37 },
38 {
39 "role": "user",
40 "content": user_prompt,
41 },
42 ]
43
44 for entry_number in range(1, 6):
45 completion = groq.chat.completions.create(
46 model="openai/gpt-oss-20b",
47 messages=messages,
48 max_tokens=1000,
49 temperature=1,
50 )
51 entry_text = completion.choices[0].message.content
52
53 Entry.objects.create(topic=topic, text=entry_text)
54 print(f"Saved entry {entry_number} for {topic_name}")
55
56print("Done! Added 5 entries for each topic.")- system_prompt holds the instructions Groq follows for every entry. The long string is split across several lines inside parentheses, and Python joins the pieces back into one string.
- The outer for loop goes through each topic one at a time. For each topic it:
- Finds the topic in the database with Topic.objects.get.
- Builds a user_prompt. The f-string puts the topic name into the prompt.
- Builds a messages list (the prompt), just like the chatbot.
- The inner for loop runs 5 times (range(1, 6) counts from 1 to 5). Each time it:
- Calls groq.chat.completions.create to generate one journal entry. Because temperature=1, each entry comes out different even though the prompt is the same.
- Pulls the text out with completion.choices[0].message.content.
- Saves the entry with Entry.objects.create, which adds one row to the Entry table. The topic=topic argument fills in the foreign key, connecting the entry to its topic.
Run the Script:
- From the folder that has manage.py, here is the process:
- Save populate_entries.py, then in the terminal run the command python populate_entries.py
- You should see output like this in the terminal:
1Saved entry 1 for Data_Types
2Saved entry 2 for Data_Types
3...
4Saved entry 5 for Lists
5Done! Added 5 entries for each topic.- Only run the script once, since every run adds 10 more entries.
Check Your Work in the Admin Site:
- Start the server with the command python manage.py runserver and login to the admin site (http://localhost:8000/admin).
- Click Entries and make sure you see 10 entries listed.
- Click on an entry to see which topic it belongs to.
Troubleshooting:
- No module named ‘code_journal’
- You are in the wrong folder, or populate_entries.py is in the wrong place. It must be in the same folder as manage.py.
- No module named ‘groq’
- Run pip install groq, then try again.
- Topic matching query does not exist
- A name in topic_names doesn’t match a topic in your database. Check the spelling in the admin site.